问题
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
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);
});
}
I am getting status: 200
in the logs but getting message 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);
}
});
I am not understanding whether the files are not found by the axios or is it the fault of Content-Type.
回答1:
Axios is creating a lot of problems with formdata
on Android
.
So I recommend using a different API.
You can use 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);
来源:https://stackoverflow.com/questions/57222377/axios-unable-to-upload-file-on-android-but-working-on-ios