React Native中使用FormData上传文件失败求助(415错误)
解决React Native中FormData上传文件返回415错误的问题
问题分析
415状态码表示不支持的媒体类型,核心原因是请求的multipart/form-data格式不符合服务器要求,或者请求头设置错误。结合你的代码,主要问题出在这几个点:
- 手动设置
Content-Type导致格式错误:当使用FormData上传文件时,HTTP客户端(如Axios)会自动生成包含boundary的multipart/form-data请求头,手动指定固定的Content-Type会丢失自动生成的boundary,服务器无法正确解析表单数据。 - FormData字段冗余:你添加的
fileName、size字段是多余的,标准FormData只需要uri、type、name三个核心字段。
修复步骤
1. 移除手动设置的Content-Type头
删除请求配置中的headers: {'Content-Type': 'multipart/form-data'},让HTTP客户端自动处理请求头。
2. 简化FormData的字段
只保留必要的字段,避免冗余导致解析问题。
修改后的完整代码
try { const pickerResult = await DocumentPicker.pickSingle({ presentationStyle: 'fullScreen', copyTo: 'documentDirectory', type: [DocumentPicker.types.pdf], mode: 'import', }); setAccountStatement(pickerResult); const data = new FormData(); data.append('file', { uri: pickerResult.fileCopyUri, type: pickerResult.type, name: pickerResult.name, }); http .post('你的上传接口URL', data) .then(response => { console.log('上传成功:', response); }) .catch(error => { console.log('上传失败:', error); }); } catch (err) { console.log('文件选择出错:', err); }
额外排查点
如果修复后仍然报错,检查以下内容:
- 确认服务器接收的字段名:确保
data.append('file', ...)中的file和服务器端期望的字段名一致(比如有些服务器要求upload、document等)。 - Android URI兼容性:如果是Android设备,尝试将
fileCopyUri的file://前缀替换为content://(不过你已经将文件复制到应用私有目录,这个操作通常不需要)。 - 文件权限:确认应用有读取文件的权限,
react-native-document-picker通常会自动处理权限,但可以检查AndroidManifest.xml中是否添加了READ_EXTERNAL_STORAGE权限。
内容的提问来源于stack exchange,提问作者Ifeoluwa Alao
相关产品推荐
相关产品推荐

