简体   繁体   中英

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. I'm using multer for saving it in the public/ folder.

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)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM