Axios 无法在 android 上传文件,但正在 iOS

Axios unable to upload file on android but working on iOS

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

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

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的错。

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