文件对象在推入数组时会变成字符串? JS [英] File object becomes string when pushed to an array? JS
问题描述
我的目标是将多个文件从Vue.js前端上传到php/Laravel后端.
My goal is to upload multiple files from a Vue.js frontend to a php/Laravel backend.
这是我收集文件的地方:
This is where I collect the files:
<input id="cover-file" @change="onCoverSelected" type="file" multiple>
这是onCoverSelected
方法:
onCoverSelected(e) {
let files = e.target.files;
// let fileArray = Object.values(files);
for (var i = 0; i < files.length; i++) {
console.log(files[1]);
this.covers.push(files[1]);
}
},
当我console.log
个文件时,它们在DevTools控制台中显示为实际文件.到目前为止一切顺利.
When I console.log
the files, they appear as actual files in the DevTools console. So far so good.
但是,当我将文件推入数组时,它们变成了字符串!我不明白为什么.我的后端依赖于接收文件对象数组.
However, when I push the files to an array, they become strings! I don't understand why. My backend depends on receiving an array of file objects.
这是DevTools的屏幕截图,其中显示了File对象变为字符串
This is a screenshot from DevTools where it shows that the File object becomes a string
这是从后端希望接收文件对象数组的地方,但是,当我dd
covers
变量时,我会收到一个空数组:
This is from my backend where I hope to receive an array of File objects, however, I receive an empty array when I dd
the covers
variable:
$covers = (array)json_decode($request->input('covers'));
dd($covers);
不使用(array)
打印以下内容:
"[object File],[object File],[object File]"
如何在后端接收File
对象的数组?谢谢.
How can I receive an array of File
objects in the backend? Thank you.
推荐答案
不幸的是,File是一个对象,代表文件的二进制信息.问题不是将它们推入数组,而是将其转换为JSON时出现的问题:它将尝试将File对象转换为字符串.在这种情况下,它不能将二进制表示为字符串,因此File只是转换为=> [object File]
.
Unfortunately, File is an object, representing the binary information of a file. The issue isn't pushing them into an array, the issue is when you convert it to JSON: it will attempt to convert the File object to a string. In this case, it can't represent binary as a string, so File is simply converted to => [object File]
.
您的2个选项是:
-
以多部分形式提交POST数据.
Submit POST data in a multipart form.
将文件转换为base64字符串,或其他类似方法. (可以在服务器端极大地影响性能,编码然后解码)
Convert the File to a base64 string, or other similar methods. (Can drastically effect performance, encoding and then decoding on server side)
在此处查看另一个相关线程.
See another related thread here.
这篇关于文件对象在推入数组时会变成字符串? JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!