[英]Multiple file upload using Laravel & Vue JS
所以我一直在嘗試在服務器端使用帶有Laravel的Vue JS上傳多個圖像文件。
我的模板vue
<input type="file" id = "file" ref="file" v-on:change="onImageChange" multiple />
我的 Javascript 代碼
<script>
export default {
data(){
return{
product: {},
image: '',
}
},
created() {
let uri = `/api/product/edit/${this.$route.params.id}`;
this.axios.get(uri).then((response) => {
this.product = response.data;
});
},
methods:{
onImageChange(e){
let files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file){
let reader = new FileReader();
let vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
replaceByDefault(e) {
e.target.src = this.src='/uploads/products/default_image.jpg';
},
saveImage(e){
e.preventDefault()
var file = document.getElementById('file').files;
let formData = new FormData;
formData.append('productId', this.product.id)
formData.append('file', file[0])
axios.post('/api/product/image/add', formData, {
headers: {'Content-Type': 'multipart/form-data'}
}).then((response) => {
this.$router.push({name: 'view',params: { id: this.product.id }});
});
}
}
}
</script>
我在互聯網的某個地方看到在 vue 中你可以使用循環formData.append但我如何在服務器端捕獲數據。 這是我的產品控制器
$saveImage = new Gallery;
$saveImage->product_id = $request->productId;
$file = request()->file('file');
$file_name = time().$file->getClientOriginalName();
$path = $imgUpload = Image::make($file)->save(public_path('/uploads/products/' . $file_name));
$saveImage->path = '/uploads/products/'.$file_name;
$saveImage->status = 1;
$saveImage->save();
return "success";
非常感謝你們!
您可以使用request()->file('file')
來獲取文件。 但是當您嘗試發送文件數組時,您必須在 vue 源中添加一些更改。
Vue
let formData = new FormData;
formData.append('productId', this.product.id)
// append files
for(let i=0; i<file.length; i++){
formData.append('file[]', file[i])
}
使用file[]
而不是file
將在請求有效負載中生成一個文件數組。 然后在代碼的 laravel 端,您可以使用request()->file('file')
來獲取該文件數組。 但如果您只想要其中一個(例如:第一個),您可以使用request()->file('file.0')
來獲取該文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.