从 React Native 上传图像文件到 C# 后端

问题描述 投票:0回答:1

我正在尝试将图像文件(任何类型)从 React Native Android 应用程序前端上传到 C# 后端代码。

这是我的反应本机代码:

import * as ImagePicker from "expo-image-picker";

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();  

};
    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 命中断点。

有人可以帮我解决这个问题吗?已经花了近 2 天的时间来解决这个问题?

谢谢。

c# .net typescript react-native api
1个回答
0
投票

尝试在方法参数中使用

[FromForm]

public async Task<ActionResult> Create([FromForm] IFormFile file) 
{
    //...
}

[FromForm]
代表您从客户端发送的文件和数据。如果您想了解,请查看此阅读内容

© www.soinside.com 2019 - 2024. All rights reserved.