我正在使用 React Native 文档选择器并选择多个文档上传到服务器上。我也使用 formData 来上传文件。但在后端我的文件没有上传。我从我这边打得最好。如果有人知道解决方案请指导。
const selectMyFiles = async () => {
try {
const results = await DocumentPicker.pick({
copyTo: 'documentDirectory',
allowMultiSelection: true,
type: [
DocumentPicker.types.pdf,
DocumentPicker.types.docx,
DocumentPicker.types.images,
],
});
let documents = [];
results.forEach(result => {
const {name, uri, size, type, fileCopyUri} = result;
const maxFileSize = size / 1048576;
if (maxFileSize <= 2) {
setSelectedFiles([
...selectedFiles,
{name, uri, size, type, fileCopyUri},
]);
documents.push({
uri: uri,
type: type,
size: size,
name: name,
fileCopyUri: fileCopyUri,
});
setModalValue(false);
} else {
Alert.alert('Max File', 'Maximum file size is 2MB', [
{
text: 'Change',
onPress: () => selectOneFile(),
style: 'cancel',
},
]);
return false;
}
});
setFilesInAction(documents);
} catch (err) {
if (DocumentPicker.isCancel(err)) {
alert('Canceled from single doc picker');
} else {
//For Unknown Error
alert('Unknown Error: ' + err);
throw err;
}
}
};
const onPressSubmit = () => {
const formData = new FormData();
formData.append('remarks', inputContactState);
formData.append('category_id', categoryId);
formData.append('documents[]', filesInAction);
dispatch(contactComplaintAction(formData));
};
我认为您的请求正文有问题
用这个身体试试
const formData = new FormData();
formData.append('remarks', inputContactState);
formData.append('category_id', categoryId);
filesInAction.forEach((file: any) => {
formData.append('documents[]', {
name: file?.fileName,
size: file?.fileSize,
type: file?.type,
uri: file?.uri
});
});
表单数据 API 示例
const uploadImage = async () => {
formData.append('remarks', inputContactState);
formData.append('category_id', categoryId);
filesInAction.forEach((file: any) => {
formData.append('documents[]', {
name: file?.fileName,
size: file?.fileSize,
type: file?.type,
uri: file?.uri
});
});
let res = await fetch(
`${baseUrl}/fame/saveImage`,
{
method: 'post',
body: formData,
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
}
);
let responseJson = await res.json();
if (responseJson.status == 1) {
alert('Upload Successful');
}
};