laravel 使用 vue js 和 axios 上传多个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54519998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload multiple file with vue js and axios
提问by weaver
I am trying to upload multiple images using vuejs and axios but on server side i am getting empty object.I added multipart/form-data in header but still empty object.
我正在尝试使用 vuejs 和 axios 上传多个图像,但在服务器端我得到了空对象。我在标题中添加了 multipart/form-data 但仍然是空对象。
submitFiles() {
/*
Initialize the form data
*/
let formData = new FormData();
/*
Iteate over any file sent over appending the files
to the form data.
*/
for( var i = 0; i < this.files.length; i++ ){
let file = this.files[i];
console.log(file);
formData.append('files[' + i + ']', file);
}
/*`enter code here`
Make the request to the POST /file-drag-drop URL
*/
axios.post( '/fileupload',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
},
}
).then(function(){
})
.catch(function(){
});
},
HTML:
HTML:
<form method="post" action="#" id="" enctype="multipart/form-data">
<div class="form-group files text-center" ref="fileform">
<input type="file" multiple="multiple">
<span id='val'></span>
<a class="btn" @click="submitFiles()" id='button'>Upload Photo</a>
<h6>DRAG & DROP FILE HERE</h6>
</div>
My Server side code:
我的服务器端代码:
class FileSettingsController extends Controller
{
public function upload(Request $request){
return $request->all();
}
}
Output:
输出:
{files: [{}]}
files: [{}]
0: {}
Console.log() result:
File(2838972)?{name: "540340.jpg", lastModified: 1525262356769, lastModifiedDate: Wed May 02 2018 17:29:16 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 2838972,?…}
Console.log() 结果:
File(2838972)?{name: "540340.jpg", lastModified: 1525262356769, lastModifiedDate: Wed May 02 2018 17:29:16 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 2838972,?…}
回答by Daniel
You forgot to use $refs
. Add ref
to your input:
你忘记使用$refs
. 添加ref
到您的输入:
<input type="file" ref="file" multiple="multiple">
Next, access your files like this:
接下来,像这样访问您的文件:
submitFiles() {
let formData = new FormData();
for( var i = 0; i < this.$refs.file.files.length; i++ ){
let file = this.$refs.file.files[i];
console.log(file);
formData.append('files[' + i + ']', file);
}
axios.post( '/fileupload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
}
).then(function(){
})
.catch(function(){
});
},
This should be work.
这应该是工作。
回答by Ahmad Hassan
If anyone wondering, "How can I send also data with it", there you go:
如果有人想知道,“我怎样才能用它发送数据”,你去吧:
formData.append('name[' + this.name + ']', name);
formData.getAll('files', 'name');