【发布时间】: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