My recent project involved uploading a single file using form-data and fetch (POST request) successfully. However, I encountered an issue when trying to upload multiple files. Here is the code snippet in question:
In the HTML part of my vue.js:
<el-button @click="post_visible = true">POST</el-button>
<el-dialog :visible.sync="post_visible" title="Adding a new value!">
<span>Image_1</span>
<input type="file" name="file1" />
<br>
<br>
<span>Image_2</span>
<input type="file" name="file2" />
<br>
<br>
<span>Image_3</span>
<input type="file" name="file3" />
<br>
<br>
<el-button @click = "submit"> Submit </el-button>
</el-dialog>
Now moving on to the Javascript section:
methods:{
submit(){
var formData = new FormData();
var fileField = document.querySelector("input[type='file']");
console.log(fileField.files.length) // Checking the length of the uploaded files.
// Attaching the files.
formData.append('file', fileField.files[0]);
formData.append('file', fileField.files[1]);
formData.append('file', fileField.files[2]);
const headers = new Headers();
headers.append('Authorization', 'Bearer '+ token); // Token has been initialized
const body = formData;
const init = {
method: 'POST',
headers,
body
};
fetch('http://*********/****', init)
.then((response) => {
return response.json(); // or .text() or .blob() ...
})
.then((text) => {
// Deal with the response data here
})
.catch((e) => {
// Handle any errors that occur
});
}
}
Upon testing this code, I received a 500 error (internal server error). After successful POST requests using tools like 'AdvancedRestClient', it became apparent that the issue lies in uploading multiple files. By checking the length of fileField.files,I discovered that only one file was being processed instead of three as expected. Further inspection revealed that the formdata object contained only one file and the values for the other two were undefined. It seems there's an error in my code related to handling multiple file uploads. Any guidance or alternative solutions would be greatly appreciated.
Thank you for your assistance.