Axios无法在Android上上传文件,但可以在iOS上使用 [英] Axios unable to upload file on android but working on iOS

查看:140
本文介绍了Axios无法在Android上上传文件,但可以在iOS上使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用React-Native中的Axios将文件上传到服务器.这些文件已在iOS上上传,但在Android上却未上传

I am trying to upload files to the server using Axios in React-Native. The files are getting uploaded on iOS but on Android they are not getting uploaded

本机Axios同步代码

React-Native Axios sync code

syncFunction() {
    var RNFS = require('react-native-fs');
    var path = RNFS.DocumentDirectoryPath + '/toBeSynced';
    RNFS.readDir(path)
    .then((files) => {
    var uploadUrl = 'http://192.168.1.15:3333/SurveyJsonFiles/GetFiles/'
    for (let i = 0; i < files.length; i++) { // looping through folder for files

        var fileName = files[i].name // Name of the file
        var filePath = files[i].path // Path of the file

        if (Platform.OS === 'android') {
            filePath = filePath.replace("file://", "")
        }

        const file = { uri: filePath, name: fileName, type: 'json' };
        const formData = new FormData();
        formData.append("files", file);

        const config = {
            headers: {
                "Accept": 'application/json',
                'Content-Type': 'application/json',
            },
            data: {},
        };

        axios.post(uploadUrl, formData, config).then((resp) => {
            console.log(resp);
            console.log(resp.data.Msg)
        }).catch(err => {
            console.log(err);
        });
    }
    })
    .catch((err) => {
        console.log(err.message);
    });
}

我在日志中收到status: 200,但收到消息data: {Status: false, Msg: "Failed to upload the File", body: {…}}

I am getting status: 200 in the logs but getting message data: {Status: false, Msg: "Failed to upload the File", body: {…}}

在192.168.1.15:3333上运行的NodeJS Multer代码

NodeJS Multer Code running on 192.168.1.15:3333

var upload = multer({
  storage: storage
});

router.post('/GetFiles', upload.single('files'), function (req, res) {

  if (req.file) {
    res.send({ "Status": true, "Msg": "File Uploaded Successfully" });
  }
  else {    
    res.send({ "Status": false, "Msg": "Failed to upload the File", "body": req.body });
  }

})

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
   cb(null, './Uploads/');
   },
  filename: function (req, file, cb) {
   cb(null, file.originalname);
   }
});

我不知道axios是否找不到文件,或者是Content-Type的错误.

推荐答案

Axios Android上的formdata上造成了很多问题. 因此,我建议使用其他API.

Axios is creating a lot of problems with formdata on Android. So I recommend using a different API.

您可以使用XMLHttpRequest

let xhr = new XMLHttpRequest();
xhr.open('POST', uploadUrl);
let formdata = new FormData();
// add json file 
formdata.append('files', { uri: filePath, name: fileName, type: 'json' });
xhr.send(formdata);

这篇关于Axios无法在Android上上传文件,但可以在iOS上使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆