React Native中Expo ImagePicker上传图片至自建服务器失败求助
问题解决:Expo ImagePicker 图片上传自建服务器失败
核心问题分析
你的代码存在两个关键错误:
- 直接将base64字符串作为
file字段值传入FormData,服务器无法识别为合法的文件格式 - 手动设置
Content-Type: multipart/form-data,覆盖了axios自动生成的包含boundary的请求头,导致服务器无法正确解析表单数据
修正后的代码实现
const [image, setImage] = useState(null); const pickImageProfile = async () => { let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [3, 4], quality: 1, // 不需要base64,直接用本地URI即可 }); if (!result.canceled) { const selectedAsset = result.assets[0]; setImage(selectedAsset.uri); fdata.client_image = selectedAsset.uri; const formData = new FormData(); // 按照React Native FormData要求构造文件对象 formData.append('file', { uri: selectedAsset.uri, name: `image_${Date.now()}.${selectedAsset.type.split('/')[1]}`, type: selectedAsset.type, }); axios.post("https://myserverforimg/upload", formData) .then((response) => { console.log('上传成功:', response); // 这里可以拿到服务器返回的图片URL,比如 response.data.url }).catch((error) => { console.error('上传失败:', error.response?.data || error.message); }); } };
关键说明
- FormData文件构造:React Native的FormData要求文件对象必须包含
uri(本地文件路径)、name(文件名)、type(MIME类型)三个字段,这样axios才能正确封装为文件上传请求 - 请求头自动生成:不要手动设置
multipart/form-data头,axios会根据FormData自动生成包含正确boundary的请求头,这是服务器解析表单的关键 - 可选:base64转文件方案:如果你的场景必须使用base64,可以将其转换为Blob后再添加到FormData,但在React Native中直接使用本地URI是更高效的方式
内容的提问来源于stack exchange,提问作者Akma
相关产品推荐
相关产品推荐

