我正在尝试使用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 = '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上使用
发布评论