0

I am trying to send an image from mobile (I took photo) and send to NodeJS from React without success. Here is the piece of code.

ReactJS

const formData = new FormData();
  formData.append("data", {
    uri: imageURI,
    name: "photo",
    type: "image/jpg",
  });

  const resp = await fetch(URL + "/send", {
    method: "POST",
     body: formData,
     headers: { "Content-Type": "multipart/form-data" }
  }).then(async (res) => {
    console.log(res);
    
  });

And here is the NodeJS code:

const express = require('express');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
const server = require("http").createServer();
const fs = require('fs');
let multiparty = require('multiparty');
const app = express();

app.use(bodyParser.urlencoded({
    extended: false,
    type: 'multipart/form-data'
}));

//https://stackoverflow.com/questions/56748415/req-body-is-empty-in-node
app.post('/send', (request, response, next) => {
    console.log(request.body);
    console.log(request.body.data);
    
    fs.writeFile('result.png', request.body, function(err) {
        console.log('File created: result.png');
    });

    response.send('uploaded!')
});


//Start the Server 
server.on("request", app);

server.listen(port, function() {
    console.info(`PPT Server: ${server.address().port}`);
});

I am getting this error.

fs.js:1253
      data : Buffer.from('' + data, options.encoding || 'utf8');
                            ^

TypeError: Cannot convert object to primitive value
    at writeFd (fs.js:1253:29)
    at fs.js:1247:7
    at FSReqCallback.oncomplete (fs.js:146:23)

How can I be able to save the uploaded image?

user3736228
  • 273
  • 3
  • 18

0 Answers0