我正在尝试将文件(Excel 工作表)从使用 VueJS 构建的前端应用程序上传到使用 Laravel 5.5 构建的 API。我有一些表单请求验证对我说The file field is required
。所以文件根本不会上传到我的 API。
VueJS文件上传:
onFileChange(e) {
let files = e.target.files || e.dataTransfer.files;
if (files.length <= 0) {
return;
}
this.upload(files[0]);
},
upload(file) {
this.form.file = file;
this.form.put('courses/import')
.then((response) => {
alert('Your upload has been started. This can take some time.');
})
.catch((response) => {
alert('Something went wrong with your upload.');
});
}
this.form
是从该项目复制的 Form 类,但该data()
方法返回FormData对象而不是对象。
data()
方法:
data() {
let data = new FormData();
for (let property in this.originalData) {
data.append(property, this[property]);
}
return data;
}
路线:
表单请求规则:
public function rules()
{
return [
'file' => 'required',
];
}
如果我查看 Chrome DevTools 中的 Network 选项卡,它似乎确实正确发送了请求:(单击后的图像)。
我尝试了很多东西,比如将excel作为base64发送到api。但后来我无法正确解码。所以现在我正在尝试这个,但我无法解决问题。
编辑(控制器功能)
public function update(ImportRequest $request, CoursesImport $file)
{
$courses = $file->handleImport();
dispatch(new StartCourseUploading($courses, currentUser()));
$file->delete();
return ok();
}