我正在使用https://github.com/itinance/react-native-fs上传文件,但是它没有向服务器发送任何请求,有时会引发套接字问题,请检查我当前使用的代码。
我已经尝试过使用表单数据进行简单的提取,但是它仅适用于ios,不适用于android
const toUrl = 'http://***';
const name = 'file_XCzY_SINGLE_FILE_POST';
const filename = 'IMG-20190514-WA0003.jpg';
const filepath = 'content://com.android.providers.media.documents/document/image%3A209152';
const filetype = 'image/jpeg';
const params = {
c2f: "HP4S",
isIOS: false,
meta_Chartfield_Number: '121212',
meta_Comments: "",
meta_Department: "%user_ldap_department%",
meta_Due_date_Poster_Order_Form: null,
meta_Due_time_Poster_Order_Form: "4 pm",
meta_Email: "%user_ldap_mail%",
meta_Name123: "%user_ldap_displayName%",
name: "file_XCzY_SINGLE_FILE_POST",
the_action: "STOR",
uploadPath: "%2FTest%2F"
};
const uploadBegin = (response) => {
const jobId = response.jobId;
console.log('UPLOAD HAS BEGUN! JobId: ' + jobId);
};
const uploadProgress = (response) => {
const percentage =
Math.floor((response.totalBytesSent/response.totalBytesExpectedToSend)
* 100);
console.log('UPLOAD IS ' + percentage + '% DONE!');
};
RNFS.uploadFiles({
toUrl: encodeURI(url),
files: [{
name
filename
filepath
filetype
}],
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Cookie': 'my-cookies*****'
},
fields: params,
begin: uploadBegin,
beginCallback: uploadBegin,
progressCallback: uploadProgress,
progress: uploadProgress
}).promise.then((response) => {
console.log(response,"<<< Response");
if (response.statusCode == 200) {
console.log('FILES UPLOADED!');
} else {
console.log('SERVER ERROR');
}
})
.catch((err) => {
if (err.description) {
switch (err.description) {
case "cancelled":
console.log("Upload cancelled");
break;
case "empty":
console.log("Empty file");
default:
//Unknown
}
} else {
//Weird
console.log('Weird')
}
console.log(err);
});
请让我知道我是否在代码中犯了任何错误,例如字段或其他任何错误,这对我真的很有帮助
谢谢。
答案 0 :(得分:0)
我也遇到了与 uploadFile
中的 react-native-fs
相同的问题。取而代之的是,我通过将内容包装在表单数据中并传递给服务器来使用 axios
。 (就我而言,我需要将 zip 文件上传/发送到服务器)。
我做了这样的事情:
const path = `${RNFS.DownloadDirectoryPath}/data.zip`;
const getFile = {
uri: `file://${path}`,
name: 'data.zip',
type: 'application/zip',
};
const formData = new FormData();
formData.append('files', getFileData);
axios
.post(`API_URL`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {})
.catch(err => {});