问题
I am using react-dropzone to get files on my react application and i am trying to upload these multiple images using axios. Backend is in mongo+express. But, for some reasons, image is not being received at the backend. MY react code is:
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,
);
The dragdrop element is below:
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>
);
On the backend, when I log req.body.images, it says [ '[object Object]', '[object Object]' ]. So, when I try to log this array, it literally logs out out every single character:
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 ]
Does anyone know what I could be possibly doing wrong? P.S. I have tried with different headers on the client side. Nothing works
回答1:
with FormData, you should add each file using a sequential name. like so:
const fd = new FormData();
files.forEach((file, index) => {
fd.set(`file[${index}]`, file, file.name);
});
your server should be able to interpret this as an array of files from the client.
来源:https://stackoverflow.com/questions/63763343/unable-to-upload-images-with-react-dropzone