在Android上反应原生上传图片

时间:2016-08-21 08:18:16

标签: android node.js react-native

我在Android上有一个react-native应用程序和一个用NodeJS + Express编写的后端服务器,我正在使用multer处理文件上传。

const multer = require('multer');
const mime = require('mime');
const crypto = require('crypto');


const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, config.uploads),

  filename: (req, file, cb) => {
    crypto.pseudoRandomBytes(16, (err, raw) => {
      cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype));
    });
  }
});


const upload = multer({ storage });


const Router = require('express').Router;
const controller = require('./upload.controller');
const router = new Router();


const auth = require('./../../auth/auth.service');


router.post('/', [auth.isAuthenticated(), upload.any()], controller.create);


module.exports = router;

在我的本机应用程序上,我尝试这样做:

ImagePicker.launchCamera(options, image => {

      let { uri } = image
      const API_URL = 'http://192.168.1.2:9000/api/uploads'

      var form = new FormData();
      form.append("FormData", true)
      form.append("access_token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU3YjgyZGQ2MTEwZDcwYmEwYjUxZjM5YyIsImlzTWVkaWMiOnRydWUsImlhdCI6MTQ3MTY4ODE1MiwiZXhwIjoxNDcxNzA2MTUyfQ.gPeql5g66Am4Txl1WqnbvOWJaD8srTK_6vihOJ6kFbY")
      form.append("Content-Type", "image/jpg")
      form.append('image', uri)

      fetch(API_URL, {body: form, mode: "FormData", method: "post", headers: {"Content-Type": "multipart/form-data"}})
        .then((response) => console.log(response))
        .catch((error) => {
          console.log("ERROR " + error)
        })
        .then((responseData) => {
          console.log("Succes "+ responseData)
        })
        .done();
    })

但是当我尝试上传时,我发现了以下错误

  

多部分正文必须至少有一部分

我做错了什么?

有人知道更好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

此时获取可能不支持Blob和FormData,但您可以改为使用XMLHttpRequest polyfill。

  let xhr = new XMLHttpRequest()
  xhr.open('post', `http://myserver.com/upload-form`)
  xhr.send(form)
  xhr.onerror = function(e) {
    console.log('err', e)
  }
  xhr.onreadystatechange = function() {
    if(this.readyState === this.DONE) {
      console.log(this.response)
    }
  }