【发布时间】:2019-04-28 05:03:55
【问题描述】:
所以我之前问过一个问题,并在logging 结果方面得到了一点帮助,但是我的结果没有意义。
所以我有意见
<input type="file" name="import_file" v-on:change="selectedFile($event)">
v-on:change将选中的文件绑定到我的数据对象this.file
selectedFile(event) {
this.file = event.target.files[0]
},
然后我用这个方法提交文件
uploadTodos() {
let formData = new FormData();
formData.append('file', this.file);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
this.$store.dispatch('uploadTodos', formData);
}
但是,当我提交时,formData 似乎没有附加数据,因为我的logged 结果是这样的
file, [object File]
我不应该将我的实际数据附加到formData 对象吗??
我参考了其他关于如何发布的文章,但我没有得到想要的结果。
uploadTodos(context, file) {
console.log(file)
axios.post('/import', file,{ headers: {
'Content-Type': 'multipart/form-data'
}})
.then(response => {
console.log(response.data)
context.commit('importTodos', response.data)
})
.catch(error => {
console.log(error.response.data)
})
}
当我console.log(file) formData 对象为空时
后端问题
所以我在后端使用 Laravel 的问题在于 maatwebsite 包。从我看到的是 3.0 版本还不支持导入。建议的唯一解决方法是安装 2.0 版?这仍然是唯一的解决方法吗?这是控制器方法
public function importExcel(Request $request)
{
if (empty($request->file('file')->getRealPath())) {
return back()->with('success','No file selected');
}
else {
$path = $request->file('file')->getRealPath();
$inserts = [];
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $rows){
foreach($rows as $row){
$inserts[] = ['user_id' => $row['user_id'], 'todo' => $row['todo']];
};
}
});
if (!empty($inserts)) {
DB::table('todos')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}
return back();
}
}
3.0版不支持的行是这样的
Excel::load($path,function($reader) use (&$inserts)
【问题讨论】:
-
一个
File封装了数据。 developer.mozilla.org/en-US/docs/Web/API/File -
您到底想达到什么目标,您遇到的错误是什么?
-
@MazinoSUkah,我正在尝试使用
this.$store.dispatch('uploadTodos', formData);提交我的表单数据对象,但是我的vuex方法uploadTodos不包含任何数据。请查看vuex方法的更新问题 -
@RoyJ,当我
console.log(pair)它显示formData对象的内容但是一旦它到达我的vuex方法它似乎是空的......
标签: vue.js file-upload axios form-data