[英]Sending multiple files to Laravel backed using Vue.js
我在 Vue.js 中使用多步骤表单将多个文件发送到 Laravel 后端。 该表单使用户能够将多个用户添加到数据库中。 每个用户都需要上传一个文件。
文件最初使用 Vuex 存储在状态中。 每个文件都被推送到 store.js 中的文件数组
当用户提交表单时,我将所有单独的表单数据(包括文件数组)添加到新的 FormData() 对象中,如下所示:
let fd = new FormData();
// append each file
for( var i = 0; i < store.state.files.length; i++ ){
let file = store.state.files[i];
fd.append('files[' + i + ']', file);
console.log(file);
}
// append rest of form data
fd.append('appointments', store.state.appointments);
fd.append('business_details', store.state.business_details);
fd.append('business_names', store.state.business_names);
fd.append('directors', store.state.directors);
fd.append('share_amount', store.state.share_amount);
fd.append('shareholders', store.state.shareholders);
添加所有表单数据后,我使用 Axios 将表单数据发送到我的 Laravel 后端。
axios.post('/businesses', fd, {
headers: {
'content-type': 'multipart/form-data'
}
})
.then(response => {
console.log(response);
this.completeButton = 'Completed';
})
.catch(error => {
console.log(error)
this.completeButton = 'Failed';
})
在我的 Laravel BusinessController 中,我想要Log::debug($_FILES)
以查看发送了哪些文件,但我得到的只是一个空数组。
[2018-10-05 16:18:55] local.DEBUG: array (
)
我已经检查过我发送的标头是否包含'multipart/form-data'
,并且我将所有表单数据附加到 new FormData() 但我无法弄清楚为什么服务器收到一个空的 $_FILES 数组。
更新 1:如果我Log::debug($request->all());
我得到:
如果我尝试将对象存储在该文件中,如下所示:
foreach ($request->input('files') as $file) {
$filename = $file->store('files');
}
我收到以下错误:
[2018-10-06 09:20:40] local.ERROR: Call to a member function store() on string
试试这个案例:
var objectToFormData = function (obj, form, namespace) {
var fd = form || new FormData();
var formKey;
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (namespace) {
formKey = namespace + '[' + property + ']';
} else {
formKey = property;
}
// if the property is an object, but not a File,
// use recursivity.
if (typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
objectToFormData(obj[property], fd, property);
} else {
// if it's a string or a File object
fd.append(formKey, obj[property]);
}
}
}
return fd;
};
参考: objectToFormData
轴:
axios.post('/businesses', fd, {
transformRequest: [
function (data, headers) {
return objectToFormData(data);
}
]
})
.then(response => {
console.log(response);
this.completeButton = 'Completed';
})
.catch(error => {
console.log(error)
this.completeButton = 'Failed';
})
尝试更改此行:
fd.append('files[' + i + ']', file);
对此:
fd.append('files[]', file);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.