Saturday 27 June 2020

Node: How to upload an image with formidable?

I want to upload multiple images to cloudinary. In my React client, I have a basic multiple files input. When I click on upload, the data is correctly sent. I use the library formidable on my server to parse the files and then upload them to cloudinary.Here is my client: uploadImages(files, 3)}/> The api request:export async function uploadImages(files, userid) { try { const images = new FormData(); images.append("fileSubmission", files[0]); const res = await ax.post( process.env.SERVER_URL + "/upload-images", images, userid ); return console.log("success", res); } catch (err) { console.log("error", err); } } And the server upload route:cloudinary.config({ cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET, }); router.post("/upload-images", (req, res) => { try { const form = formidable({ multiples: true }); form.parse(req, async (_, fields, files) => { if (files) { const image = await cloudinary.uploader.upload(files, { resource_type: "image", public_id: `users/${req.userid}/${files.name}`, crop: "scale", quality: "auto", }); console.log("img uploaded", image.secure_url); return res.json({ image: image.secure_url }); } }); } catch (err) { return res.json(err); } }); It doesn't work. Would you know how to fix it? I know the server code misses a loop to upload all the files one after another. But when i did so, it said files.forEach is not a function. Anyways, this code still doesn't work even with a single image.The error is:TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type object at validateStringIf I console.log files once parsed by formidable, the result is:files { fileSubmission: File { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, size: 1813438, path: '/var/folders/hk/l5zpqnyh0000gn/T/upload_38a0a539fa77165b', name: 'filename.png', type: 'image/png', hash: null, lastModifiedDate: 2020-06-27T16:30:33.486Z, _writeStream: WriteStream { _writableState: [WritableState], writable: false, _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, path: '/var/folders/hk/l5zpqnyh0000gn/T/upload_38a0a539fa77165b', fd: null, flags: 'w', mode: 438, start: undefined, autoClose: true, pos: undefined, bytesWritten: 1813438, closed: false } } } Thanks!

Submitted June 27, 2020 at 06:45PM by MonsieurLeland

No comments:

Post a Comment