[英]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.