Thursday, 24 May 2018

From an image to string in an axios request

So I need to pass an image(and text) from a react component to an api.I have this code in my react api:export const addProject = (name, imgs) => {var imgsArray = [];Object.keys(imgs).map(x => imgsArray.push(imgs[x]));console.log(imgsArray); //Will print(with 3 files passed): (3) [File(179582), File(32123), File(122404)]var formData = new FormData();formData.append("name", name);formData.append("images", imgsArray);return axios.post('/api/addProject',formData,{ headers: {'Content-Type': 'multipart/form-data' }});}So far we have an image object and have passed it in a formData object via a post request to the node js api.This calls the function below(removed most of the code as it's irrelevant to my problem:router.post('/addProject', upload.array('file'), (req, res) => {console.log(typeof req.body.images); //Will print out stringconsole.log(req.body.images); //Will print(with 3 files passed): [object File],[object File],[object File]});So I'm passing the file through but it's been converted to a string. I've spent ages trying to fix this to no avail.Thanks for any help!

Submitted May 24, 2018 at 06:24PM by thelynched

No comments:

Post a Comment