问题描述
我正在使用react-dropzone在我的React应用程序上获取文件,并且我试图使用axios上传这些多个图像。后端在mongo + express中。但是,由于某些原因,后端没有收到图像。 我的反应代码是:
const data = new FormData();
data.append("title",entry.title);
entry.images.forEach((image,index) => {
console.log(image)
/*This prints out
File
lastModified: 1599303132607
name: "name.jpg"
path: "name.jpg"
size: 41142
type: "image/jpeg"
webkitRelativePath: ""
*/
data.append("images",{
name: "image" + index,type: "image/jpeg",uri: image,});
});
return http.post(
"/" + dataEndPoint,data,);
拖放元素如下:
const handleDrop = (acceptedFiles) => {
setFileNames(acceptedFiles.map((file) => file.name));
files(acceptedFiles);
};
return (
<div
style={{
textAlign: "center",padding: 20,borderRadius: 0.2,borderStyle: "dashed",backgroundColor: "#fafafa",color: "#bdbdbd",marginBottom: 10,}}
>
<Dropzone
onDrop={handleDrop}
accept="image/*"
// minSize={1024}
// maxSize={3072000}
>
{({
getRootProps,getInputProps,isDragActive,isDragAccept,isDragReject,}) => {
// additional CSS depends on dragging status
const additionalClass = isDragAccept
? "accept"
: isDragReject
? "reject"
: "";
return (
<div
{...getRootProps({
className: `dropzone ${additionalClass}`,})}
>
<input {...getInputProps()} />
<span>{isDragActive ? "?" : "?"}</span>
<p>Drag'n'drop images,or click to select files</p>
</div>
);
}}
</Dropzone>
{fileNames.length > 0 && (
<div>
<strong>Images:</strong>
<ul>
{fileNames.map((fileName) => (
<li key={fileName}>{fileName}</li>
))}
</ul>
</div>
)}
</div>
);
在后端,当我登录req.body.images时,显示为 ['[object Object]','[object Object]'] 。 因此,当我尝试记录此数组时,它实际上注销了每个字符:
1 o
2 b
3 j
4 e
5 c
6 t
7
8 O
9 b
10 j
11 e
12 c
13 t
14 ]
有人知道我可能做错了什么吗? 附言我尝试了在客户端使用不同的标头。没用
解决方法
对于FormData,您应该使用顺序名称添加每个文件。像这样:
const fd = new FormData();
files.forEach((file,index) => {
fd.set(`file[${index}]`,file,file.name);
});
您的服务器应该能够将此解释为来自客户端的文件数组。