将图像从移动设备发送到Node js服务器

时间:2020-07-24 06:15:57

标签: javascript node.js react-native mobile

我试图从移动设备发送图像(我拍了照片),然后从React发送到NodeJS,但没有成功。 这是代码段。

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);
    
  });

这是 NodeJS代码

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}`);
});

我收到此错误。

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)

如何保存上载的图像?

0 个答案:

没有答案