React Native Android端上传图片至C#后端失败求助
问题:React Native Android 上传图片至C#后端无响应
我正尝试从React Native Android应用前端上传任意类型的图片至C#后端。其他API接口均可正常调用,后端用Postman测试也能触发断点,但前端上传始终失败。
React Native 前端代码
import * as ImagePicker from "expo-image-picker"; import { useState, Pressable, Text, SafeAreaView, Alert } from 'react-native'; export default function AdminPortal() { const [image, setImage] = useState<ImagePicker.ImagePickerResult | null>(null); const handleSubmit = () => { const formData = new FormData(); if (image && !image.canceled) { const fileUri = image.assets[0].uri; const fileType = image.assets[0].type; const fileName = image.assets[0].fileName; formData.append("file", { uri: fileUri, type: fileType, name: fileName, }); } fetch('http://192.168.4.25:7018/post', { method: 'POST', body: formData, }) .then((response) => response.json()) .then((response) => { console.log('upload succes', response); }) .catch((error) => { console.log('upload error', error); }); Alert.alert("Data submitted", JSON.stringify(data)); // navigation.goBack(); }; // 缺失的图片选择函数 const handleImageUpload = async () => { let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, quality: 1, }); if (!result.canceled) { setImage(result); } }; return ( <SafeAreaView style={styles.container}> <Text style={styles.header}>Admin Page</Text> <Pressable style={styles.button} onPress={handleImageUpload}> <Text style={styles.buttonText}>Upload Image</Text> </Pressable> {image && !image.canceled && ( <Text>Image selected: {image.assets[0].fileName}</Text> )} <Pressable style={styles.submitButton} onPress={handleSubmit}> <Text style={styles.buttonText}>Submit</Text> </Pressable> </SafeAreaView> ) }
C# 后端代码
[HttpPost] public async Task<ActionResult> Create(IFormFile file) { try { var imageUrl = new ImageHandler(_cloudinary).ImageUploader(file); _logger.LogInformation("A new post has been created"); return Ok(new { message = "A new post has been created" }); } catch (Exception ex) { return StatusCode(500, new { message = ex.Message }); } }
补充信息
- 其他类型API均可正常调用,应用已成功连接后端
- 后端代码无问题,使用PostMan选择文件可触发断点
解决方案
1. 修复FormData的Android URI格式问题
Expo ImagePicker在Android上返回的uri是file://开头的本地路径,直接传入FormData会导致后端无法解析。需要调整URI格式,并补充兜底的MIME类型和文件名:
import { Platform } from 'react-native'; // 在handleSubmit中修改formData.append部分 formData.append("file", { uri: Platform.OS === 'android' ? fileUri : fileUri.replace('file://', ''), type: fileType || 'image/jpeg', // 兜底标准MIME类型 name: fileName || 'uploaded-image.jpg', // 兜底文件名 });
2. 手动设置正确的请求头
fetch不会自动为FormData设置multipart/form-data头,需要手动指定(不要手动添加boundary,React Native会自动生成):
fetch('http://192.168.4.25:7018/post', { method: 'POST', headers: { 'Content-Type': 'multipart/form-data', }, body: formData, })
3. 确认权限配置
确保在app.json中添加Android文件读取权限:
{ "expo": { "android": { "permissions": [ "READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE" ] } } }
4. 调试请求内容
可以通过以下方式排查请求问题:
- 在前端添加
console.log(formData)查看FormData结构 - 使用Charles或Fiddler抓包,确认请求的
multipart/form-data格式是否正确 - 检查后端接收的
IFormFile是否为null,是否有绑定错误日志
内容的提问来源于stack exchange,提问作者Ritcus
相关产品推荐
相关产品推荐

