[英]How can I save an image sent from my NextJS client to my NodeJS server?
I was trying a few weeks ago to upload an image to my NodeJS server and, from there, save it to an S3 bucket, but I'm stuck on the first part and my server doesn't receive the image.几周前,我尝试将图像上传到我的 NodeJS 服务器,然后从那里将其保存到 S3 存储桶,但我被困在第一部分,我的服务器没有收到图像。 I'm using multer
for saving it in the public/
folder.我正在使用multer
将其保存在public/
文件夹中。
This is what I have in my client:这是我在我的客户中拥有的:
const onSubmit = async (data: any) => {
const image = data.file[0];
const params: RequestInit = {
method: 'POST',
headers: {
'Content-Type': `multipart/form-data`,
'Accept': 'image/*'
},
body: JSON.stringify(data)
};
await fetch('/api/post/create-post', params);
// Upload image to S3 Bucket
// Save post to db
}
I was setting a boundary in the Content-Type
with data=${JSON.stringify(data)}
, and when I log the headers of my request before trying to save the image, there is no "boundary" and instead I receive this error Error: Multipart: Boundary not found
(This error is shown in my server console)我用data=${JSON.stringify(data)}
在Content-Type
中设置了一个边界,当我在尝试保存图像之前记录我的请求的标头时,没有“边界”,而是我收到了这个错误Error: Multipart: Boundary not found
(此错误显示在我的服务器控制台中)
And this is what I have in my server:这就是我在我的服务器中拥有的:
const upload = multer({
dest: 'public/'
})
const router = express.Router();
router.post('/', (req, res, next) => {
console.log(req.headers);
next();
}, upload.single('photo'), (req, res) => {
console.log(req.file);
res.json({ success: true });
})
module.exports = router;
You can remove the content type from the Axios headers and let Axios set it by itself.您可以从 Axios 标头中删除内容类型,并让 Axios 自行设置。
const onSubmit = async (data: any) => {
const image = data.file[0];
const params: RequestInit = {
method: 'POST',
body: JSON.stringify(data)
};
await fetch('/api/post/create-post', params);
// Upload image to S3 Bucket
// Save post to db
}
You can check this link for the boundaries error.您可以检查此链接以了解边界错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.