问题
I am trying to post form data using JS fetch API, also i successfully send data and get response , but got an error in file uploaded my file is not uploaded , and also not get stored filename into database.
<form id="signup">
<label for="myName">Send me your name:</label>
<input type="text" id="myName" name="name" value="abc">
<br>
<label for="userId">your id:</label>
<input type="text" id="userId" name="id" value="123">
<br>
<label for="pic">your photo:</label>
<input id="profile" name="profile" id="profile" type="file">
<br>
<input id="postSubmit" type="submit" value="Send Me!">
</form>
And javascript code
const thisForm = document.getElementById('signup');
const profile = document.getElementById('profile');
thisForm.addEventListener('submit', async function (e) {
e.preventDefault();
const formData = new FormData(thisForm).entries()
formdata.append("profile",profile.files[0]);
const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: JSON.stringify(Object.fromEntries(formData))
});
const result = await response.json();
console.log(result);
回答1:
No need to transform to JSON, and no need to use entries()
on FormData. Also check the spelling, you wrote formdata
which is different than formData
.
const thisForm = document.getElementById('signup');
var formData = new FormData(thisForm);
const profile = document.getElementById('profile');
formData.append("profile", profile.files[0]);
const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
});
回答2:
For file uploading, you need Content-type multipart/form-data
. Or just leave out Content-type, because your browser will probably automatically set this.
来源:https://stackoverflow.com/questions/61137025/how-do-i-post-form-data-and-upload-file-with-the-js-fetch-api