[英]Multiple file upload using Laravel & Vue JS
so I've been trying to upload multiple image file using Vue JS with Laravel at server side.所以我一直在尝试在服务器端使用带有Laravel的Vue JS上传多个图像文件。
My template vue我的模板vue
<input type="file" id = "file" ref="file" v-on:change="onImageChange" multiple />
My Javascript code我的 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>
I saw somewhere the internet that in vue you can use looping the formData.append but how do i catch the data in the server side.我在互联网的某个地方看到在 vue 中你可以使用循环formData.append但我如何在服务器端捕获数据。 Here is my ProductController这是我的产品控制器
$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";
Thank you very much guys!非常感谢你们!
you can use request()->file('file')
to get files.您可以使用request()->file('file')
来获取文件。 but you have to add some changes in your vue source when you are trying to send an array of files.但是当您尝试发送文件数组时,您必须在 vue 源中添加一些更改。
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])
}
useing file[]
instead of file
will generate an array of files in request payload.使用file[]
而不是file
将在请求有效负载中生成一个文件数组。 then in laravel side of code you can use request()->file('file')
to get that array of files.然后在代码的 laravel 端,您可以使用request()->file('file')
来获取该文件数组。 but if you want just one of them (for example: first one) you can use request()->file('file.0')
to get that file.但如果您只想要其中一个(例如:第一个),您可以使用request()->file('file.0')
来获取该文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.