我正在使用 react-native-document-picker 和 rn-fetch-blob 上传文件。对于单个文件,它按预期工作。但我无法将多个文件上传到服务器。
上传功能
const uploadPic=()=>{
// alert('ddf');
RNFetchBlob.fetch('POST', 'http://localhost/test.upload.php', {
Authorization : "Bearer access-token",
otherHeader : "foo",
'Content-Type' : 'multipart/form-data',
}, [
// element with property `filename` will be transformed into `file` in form data
{name : 'image', filename : singleFile.name, type: singleFile.type, data: RNFetchBlob.wrap(singleFile.uri)}
]).then((resp) => {
console.log(resp);
alert('your image uploaded successfully');
})
}
上传单个文件可以正常工作,但我需要上传多个文档。
选择功能
let selectFile = async () => {
//Opening Document Picker to select one file
try {
const res = await DocumentPicker.pick({
//Provide which type of file you want user to pick
type: [DocumentPicker.types.allFiles],
//There can me more options as well
// DocumentPicker.types.allFiles
// DocumentPicker.types.images
// DocumentPicker.types.plainText
// DocumentPicker.types.audio
// DocumentPicker.types.pdf
});
//Printing the log related to the file
console.log('res : ' + JSON.stringify(res));
//Setting the state to show single file attributes
setSingleFile(res);
} catch (err) {
setSingleFile(null);
//Handling any exception (If any)
if (DocumentPicker.isCancel(err)) {
//If user canceled the document selection
alert('Canceled from single doc picker');
} else {
//For Unknown Error
alert('Unknown Error: ' + JSON.stringify(err));
throw err;
}
}
};
const res = await DocumentPicker.pick({
我把这条线从const res = await DocumentPicker.pickMultiple({
在控制台中,所有文件的数组都被发布。
现在我需要将所有文件上传到服务器,寻找一种解决方案来循环 RNFetchBlob.fetch 中的所有数据。
我在函数中添加了循环,如下所示
const uploadPic=()=>{
// alert('ddf');
RNFetchBlob.fetch('POST', 'http://localhost/test.upload.php', {
Authorization : "Bearer access-token",
otherHeader : "foo",
'Content-Type' : 'multipart/form-data',
}, [ singleFile.map((item, key) => (
{name : 'image[]', filename : item.name, type: item.type, data: RNFetchBlob.wrap(item.uri)}
))
// element with property `filename` will be transformed into `file` in form data
]).then((resp) => {
console.log(resp);
alert('Document uploaded successfully');
})
}
在控制台中我现在得到的错误
RNFetchBlob failed to create request multipart body :com.facebook.react.bridge.ReadableNativeArray cannot be cast to com.facebook.react.bridge.ReadableNativeMap
[Tue Jun 23 2020 05:36:26.918] WARN Attempt to invoke virtual method 'int java.io.InputStream.read(byte[], int, int)' on a null object reference
[Tue Jun 23 2020 05:36:27.363] LOG {"array": [Function anonymous], "base64": [Function anonymous], "blob": [Function anonymous], "data": "{\"Message\":\"sorry\",\"Status\":\"Error\"}",