Unable to upload file to server using Node.js and React Native

时间秒杀一切 提交于 2019-12-11 14:42:24

问题


We are facing a very strange behavior in our application.

We have a Node.js server running on Heroku. Our client is a React native application trying to send an file to our server.

Front-end code:

import ImagePicker from "react-native-image-picker";

class MyComponent extends React.Component {

...    

handleGallery = () => {
  ImagePicker.showImagePicker(pickerOptions, response => {

  const { uri, type, fileName } = response;
  const data = new FormData();

  data.append("data", { uri, type, name: `photo.${fileName}` });

  this.submitMultpart(data)
    .then(res => {
      console.log(res);
    })
    .catch(err => {
      console.log(err);
    });
   }
  });
 };

 submitMultpart = formData => {
  return new Promise((resolve, reject) => {
  const URL = "https://example.com/api/upload";

  const options = {
    method: "POST",
    body: formData,
    headers: {
      Accept: "application/json",
      "Content-Type": "multipart/form-data; boundary=6ff46e0b6b5148d984f148b6542e5a5d",
    }
  };

  fetch(URL, options)
    .then(res => {
      console.log(res);
      resolve(res);
    })
   .catch(err => {
      console.log(JSON.stringify(err));
      reject(err);
   });
 });
};
}

Back-end code:

const multiparty = require("multiparty");

app.post("/api/upload", async (req, res) => {
  const form = new multiparty.Form();

  form.parse(req, async (error, _fields, files) => {
    if (error) {
      console.error(error);
      return res.status(500).json({ success: false });
    }

    // Do some stuff here


    return res.status(200).json({ success: true });
  });
});

The error I'm getting in the node.js console is this:

{
  BadRequestError: stream ended unexpectedly
  at Form.<anonymous>(/app/node_modules / multiparty / index.js: 759: 24)
  at Form.emit(events.js: 194: 15)
  at finishMaybe(_stream_writable.js: 641: 14)
  at endWritable(_stream_writable.js: 649: 3)
  at Form.Writable.end(_stream_writable.js: 589: 5)
  at IncomingMessage.onend(_stream_readable.js: 629: 10)
  at Object.onceWrapper(events.js: 277: 13)
  at IncomingMessage.emit(events.js: 194: 15)
  at endReadableNT(_stream_readable.js: 1103: 12)
  at process._tickCallback(internal / process / next_tick.js: 63: 19) message: 'stream ended unexpectedly'
}

p.s: The headers are properly set by the FETCH api. We are receiving them on the back-end.

p.s2: Using postman, I'm able to send files to my server (using the same headers that I've used in the FETCH api. The request is parsed successfully in the back-end and I'm receiving the file)

p.s3: The file I'm trying to send is very small, so seems that the size of the file is not a problem here.

p.s4: I'm using a random boundary in the headers of the request because, without that, I'm getting this error:

{ 
  BadRequestError: content-type missing boundary
  at Form.parse (/app/node_modules/multiparty/index.js:180:21)
  at app.post (/app/routes/api/personalDocumentRoute.js:12:10)
  at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
  at next (/app/node_modules/express/lib/router/route.js:137:13)
  at admin.auth.verifyIdToken.then.firebaseUser (/app/middlewares/requireFirebaseLogin.js:26:14)
  at process._tickCallback (internal/process/next_tick.js:68:7) message: 'content-type missing boundary' 
}

Additional info:

package.json:

"react": "16.6.3",
"react-native": "0.58.3",

Any help would be amazing. A lot of hours debugging without success :/


回答1:


I had the same problem.

Try this:

  headers: { 
        'Accept': 'multipart/form-data',
        'Content-Type': 'multipart/form-data',
      }


来源:https://stackoverflow.com/questions/54846002/unable-to-upload-file-to-server-using-node-js-and-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!