I'm having trouble uploading multiple files and I can't seem to figure out what's causing the issue. Everything works fine when I upload just one file, but when I try to modify the code for multiple files, it doesn't work properly. (I'm new to this as well).
Here is the code snippet:
methods: {
// File change event handler
onFileChange(e) {
this.filename = "";
var names;
var link;
var keys = Object.keys(e.target.files);
console.log(e.target.files);
this.numberOfFiles = keys.length;
console.log("# of files:" + this.numberOfFiles);
if (keys.length <= 1) {
this.filename = e.target.files[0].name;
} else {
for (var i = 0; i < keys.length; i++) {
if (e.target.files[i].size > 5000000) {
console.log(e.target.files[i].name + " is too big.");
} else {
this.filename += e.target.files[i].name + ", ";
}
}
}
for (var i = 1; i <= this.numberOfFiles; i++) {
this.file = e.target.files[i];
}
link = "localhost:8080/upload" + this.filename;
console.log("names: " + names);
},
// Form submission method
submitForm(e) {
e.preventDefault();
let currentObj = this;
const config = {
headers: {
"content-type": "multipart/form-data",
"X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')
.content
}
};
let formData = new FormData();
for (var i = 1; i <= this.numberOfFiles; i++) {
formData.append('file[' + i + ']', this.file[i]);
}
// Send upload request using Axios
axios
.post("/store_file", formData, config)
.then(function(response) {
currentObj.success = response.data.success;
currentObj.failed = response.data.failed;
currentObj.filename = "";
})
.catch(function(error) {
currentObj.failed = "No file attached.";
console.log("No file attached");
});
}
}
};
Below is the HTML template:
<template>
<b-card class="card" style="margin-top: 50px;">
<div style="min-height: 100vh; width: 100%;">
<Notification v-if="success !== ''" :text="success" />
<Notification v-if="failed !== ''" :text="failed" />
</div>
<div class="text-center">
<h2>PDF Upload</h2>
<br />
<div style="max-width: 500px; margin: 0 auto;">
<form @submit="submitForm" enctype="multipart/form-data">
<div class="input-group">
<div class="custom-file">
<input type="text" placeholder="Email" name="email" id="text" autocomplete="off" />
<input
type="file"
name="filename[]"
class="custom-file-input"
id="inputFileUpload"
multiple
v-on:change="onFileChange"
/>
<label class="custom-file-label" for="inputFileUpload"></label>
</div>
<div class="input-group-append">
<input type="submit" class="btn btn-primary" value="Upload" />
</div>
</div>
<br />
<p v-if="filename !== ''" class="text-danger font-weight-bold">Selected: {{filename}}</p>
</form>
</div>
</div>
</b-card>
</template>
Current output:
Array
(
[file] => Array
(
[1] => undefined
[2] => undefined
[3] => undefined
[4] => undefined
)
)