【问题标题】:Axios unable to upload file on android but working on iOSAxios 无法在 android 上上传文件但在 iOS 上工作
【发布时间】:2019-12-04 22:28:51
【问题描述】:

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

React-Native Axios 同步代码

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: {…}}

NodeJS Multer 代码在 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的问题。

【问题讨论】:

  • 在标题中试试这个:Content-Type: multipart/form-data
  • @NajamusSaqib 已经尝试过,以及其他内容类型
  • @hongdevelop 也试过了,还是不行。它给出一个错误“错误:请求失败,状态码为 500”
  • 为什么你在Android上要更改文件路径?
  • 因为即使我删除了文件更改代码,android 也会在任何文件路径之前添加 file:// 前缀,它会给出相同的错误。

标签: javascript node.js react-native axios multer


【解决方案1】:

AxiosAndroid 上用formdata 制造了很多问题。 所以我建议使用不同的 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多