为什么文件没有从反应前端上传到后端
Why files are not being uploaded in the back-end from react-front-end
最近我开始做一个项目,我使用 react 作为前端,node 作为后端。在这个项目中,我有一个需求,从前端上传多张图片,我的后端会接收这些文件,并将它们上传到cloudinary。我为此创建了一条 API 路线。哪个工作得很好!但是当我试图从我的反应前端做同样的事情时,我没有收到任何文件只是得到一个空 [] 但是当我使用邮递员时,我在一个数组中正确地接收了所有文件。这里的问题是什么?我想这是我前端的问题。但是我不知道是什么问题。
我分享我的前后端代码:-
前端
const Upload = () => {
const [fileAra, setFileAra] = useState([]);
// for sending these files to the back-end
async function uploadProduct() {
try {
const formData = new FormData();
formData.append("assets", fileAra);
const res = await fetch("/get_product/post_product", {
method: "POST",
body: formData,
});
const body = await res.json();
if (res.status === 200) {
history.push(`/profile/${user._id}`);
toast.dark(body.message);
}
} catch (err) {
console.log(err);
}
}
return (
<input type="file" multiple onChange={(e) => setFileAra(e.target.files)} />
<button onClick={uploadProduct}></button>
)
}
后端路由
router.post(
"/post_product",
checkAuth,
multer.array("assets", 10),
async function(req, res, next) {
try {
const pictureFiles = req.files;
// map through images and create a promise array using cloudinary upload function
const multiplePicturePromise = pictureFiles.map((picture) =>
cloudinary.uploader.upload(picture.path, {
folder: `devR-Commerce/products/${req.user.name}`,
})
);
const imageResponses = await Promise.all(multiplePicturePromise);
// separating each of the images into objects
const allImagesSeparatedInObject = imageResponses.map((img) => ({
photoId: img.public_id,
photoUrl: img.secure_url,
}));
// creating a new product instance
const newProduct = new Product({
user: req.user._id,
images: allImagesSeparatedInObject,
});
// saving the product in my database
const savedProduct = await newProduct.save();
// creating relation between these two collections: Product and User
await User.updateOne(
{ _id: req.user._id },
{ $push: { products: savedProduct._id } }
);
res
.status(200)
.json({ message: "Product uploaded successfully", newProduct });
} catch (err) {
next(err);
}
},
);
注意:后台路由正常,我用Postman测试过。但是当我尝试从我的前端发送相同的文件时,我没有收到任何文件。可能是前端的问题。如果你知道答案,请帮助我。如果您需要有关此问题的任何其他信息,请随时询问。感谢您查看此内容
您需要将每个文件一个一个地附加到 FormData 而不是一次附加整个数组,就像这样。
async function uploadProduct() {
try {
const formData = new FormData();
for (let i = 0; i < fileAra.length; i++) {
formData.append(fileAra[i].name, fileAra[i])
}
const res = await fetch("/get_product/post_product", {
method: "POST",
body: formData,
});
const body = await res.json();
if (res.status === 200) {
history.push(`/profile/${user._id}`);
toast.dark(body.message);
}
} catch (err) {
console.log(err);
}
}
您可以查看此article 解释 FormData 以获取更多详细信息
最近我开始做一个项目,我使用 react 作为前端,node 作为后端。在这个项目中,我有一个需求,从前端上传多张图片,我的后端会接收这些文件,并将它们上传到cloudinary。我为此创建了一条 API 路线。哪个工作得很好!但是当我试图从我的反应前端做同样的事情时,我没有收到任何文件只是得到一个空 [] 但是当我使用邮递员时,我在一个数组中正确地接收了所有文件。这里的问题是什么?我想这是我前端的问题。但是我不知道是什么问题。
我分享我的前后端代码:-
前端
const Upload = () => {
const [fileAra, setFileAra] = useState([]);
// for sending these files to the back-end
async function uploadProduct() {
try {
const formData = new FormData();
formData.append("assets", fileAra);
const res = await fetch("/get_product/post_product", {
method: "POST",
body: formData,
});
const body = await res.json();
if (res.status === 200) {
history.push(`/profile/${user._id}`);
toast.dark(body.message);
}
} catch (err) {
console.log(err);
}
}
return (
<input type="file" multiple onChange={(e) => setFileAra(e.target.files)} />
<button onClick={uploadProduct}></button>
)
}
后端路由
router.post(
"/post_product",
checkAuth,
multer.array("assets", 10),
async function(req, res, next) {
try {
const pictureFiles = req.files;
// map through images and create a promise array using cloudinary upload function
const multiplePicturePromise = pictureFiles.map((picture) =>
cloudinary.uploader.upload(picture.path, {
folder: `devR-Commerce/products/${req.user.name}`,
})
);
const imageResponses = await Promise.all(multiplePicturePromise);
// separating each of the images into objects
const allImagesSeparatedInObject = imageResponses.map((img) => ({
photoId: img.public_id,
photoUrl: img.secure_url,
}));
// creating a new product instance
const newProduct = new Product({
user: req.user._id,
images: allImagesSeparatedInObject,
});
// saving the product in my database
const savedProduct = await newProduct.save();
// creating relation between these two collections: Product and User
await User.updateOne(
{ _id: req.user._id },
{ $push: { products: savedProduct._id } }
);
res
.status(200)
.json({ message: "Product uploaded successfully", newProduct });
} catch (err) {
next(err);
}
},
);
注意:后台路由正常,我用Postman测试过。但是当我尝试从我的前端发送相同的文件时,我没有收到任何文件。可能是前端的问题。如果你知道答案,请帮助我。如果您需要有关此问题的任何其他信息,请随时询问。感谢您查看此内容
您需要将每个文件一个一个地附加到 FormData 而不是一次附加整个数组,就像这样。
async function uploadProduct() {
try {
const formData = new FormData();
for (let i = 0; i < fileAra.length; i++) {
formData.append(fileAra[i].name, fileAra[i])
}
const res = await fetch("/get_product/post_product", {
method: "POST",
body: formData,
});
const body = await res.json();
if (res.status === 200) {
history.push(`/profile/${user._id}`);
toast.dark(body.message);
}
} catch (err) {
console.log(err);
}
}
您可以查看此article 解释 FormData 以获取更多详细信息