2016-08-21 95 views
1

我在Android上有一個反應原生應用程序,後端服務器是用NodeJS + Express編寫的,我使用Muller來處理文件上傳。在Android上反應原生上傳圖片

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

但是,當我嘗試上載我recive以下錯誤

多體必須在至少有一部分

我做錯了什麼?

有沒有人知道更好的解決方案來做到這一點?

回答

2

取此時可能不支持Blob和FormData,但可以使用XMLHttpRequest填充。

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