[英]Sending image to backend using multar post and axios
The main problem is that when I am uploading the data, after making a payload to Axios.主要问题是,当我上传数据时,在对 Axios 进行了有效载荷之后。 Only the body part is getting uploaded.
只有正文部分正在上传。 The image part is not getting uploaded.
图片部分未上传。
submit = (event) => {
event.preventDefault();
const payload = {
img: this.state.img,
body: this.state.body,
};
axios({
url: "/api/save",
method: "POST",
data: payload,
})
.then((response) => {
console.log("data has been sent to the server RESPONSE: ", response);
this.resetUserInput();
this.getBlogPost();
})
.catch((err) => {
console.log("Data is not posted: and payload is :", payload);
});
This is code for my submit button.这是我的提交按钮的代码。 And this is called to multer and there I am trying to upload the image.
这被称为 multer,我正在尝试上传图像。 Here payload is showing the image while doing console.log(), but after passing to axios and multer, The response that we are receiving doesn't have the img.
这里的有效载荷在执行 console.log() 时显示图像,但在传递给 axios 和 multer 之后,我们收到的响应没有 img。 img is just an empty object in the response.
img 在响应中只是一个空的 object 。
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "../uploads");
},
filename: function (req, file, cb) {
cb(null, file.fieldname + "-" + Date.now());
},
});
const upload = multer({ storage: storage });
router.post("/save", upload.single("img"), (req, res) => {
const data = {
body: req.body.body,
img: {
data: req.file,
contentType: "image/png",
},
};
const newBlogPost = new BlogPost(data);
console.log(newBlogPost);
newBlogPost.save((err, val) => {
if (err) {
res.status(500).json({ msg: "Sorry, The data couldn't be saved" });
console.log("Reached the save errors!");
return;
}
// console.log("printing the req here: ", req);
res.json(val);
});
});
Here also, when I console.log the newBlogPost, there is no image.在这里,当我 console.log 新博客帖子时,也没有图像。 req.file should be containing img, but it is undefined.
req.file 应该包含 img,但它是未定义的。 I also tried it using from-data, but didn't work.
我也尝试使用 from-data,但没有奏效。
Anyone here who can help!这里的任何人都可以提供帮助!
You can't just put a file in the body.您不能只将文件放在正文中。 You need to use form-data w/ axios:
您需要使用带有 axios 的表单数据:
const data = new FormData();
data.append("img", fileInput.files[0], "filepath.jpg");
Also you can append other data in formData.您也可以在 formData 中使用 append 其他数据。 Refer to this url, https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
参考这个 url, https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.