在React Native(Expo)中上传图片,使用抓取会导致400错误 [英] Image upload in React Native (Expo), using fetch results in 400 error

查看:285
本文介绍了在React Native(Expo)中上传图片,使用抓取会导致400错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天来我一直在努力上传图片. 我正在使用这样的formdata:

I have been struggling with image upload for days. I’m using formdata like this:

let formData = new FormData();
formData.append('file', {
  uri: uri,
  name: `name`,
  type: `image/jpeg`,
});

iOS上的

uri与Android上的asset-library://asset/path类似,就像content://media/external/images/media/25377.

uri on iOS is something like asset-library://asset/path on Android it is like content://media/external/images/media/25377.

let options = {
  method: 'POST',
  body: formData,
  headers: {
    Accept: 'application/json',
    'Authorization': 'Bearer ' + token,
  },
};
let response = await fetch("https://myserverurl", options)

我尝试了所有技巧,将图像读取为斑点,删除了内容类型,以及其他类似axios的库等. 不管我总是得到400错误的文件格式错误.

I tried every trick reading the image as blob, removing content-type, other libraries like axios, etc… No matter what I always get back a 400 bad file format error.

formdata是否缺少某些内容? (在后端,我们使用ASP.NET)

Is there something I’m missing with formdata? (On the backend we use ASP.NET)

推荐答案

我们遇到了类似的问题,并能够通过以下方式解决该问题. 我们正在使用NodeJS后端(带有multer)来处理文件上传.

We have had a similar issue and were able to solve the issue the following way. We are using a NodeJS backend (with multer) to handle the file uploads.

Expo-移动应用代码

  // extract the filetype
  let fileType = uri.substring(uri.lastIndexOf(".") + 1);

  let formData = new FormData();

  formData.append("photo", {
    uri,
    name: `photo.${fileType}`,
    type: `image/${fileType}`
  });

  let options = {
    method: "POST",
    body: formData,
    headers: {
      Accept: "application/json",
      "Content-Type": "multipart/form-data"
    }
  };

我们正在使用fetch(apiUrl, options)执行请求.

We are executing the request with fetch(apiUrl, options).

在我们的案例中,uri是照片的本地文件路径(例如完整的URI,例如file:///...),而apiUrl是服务器端的端点.

The uri is the local file path (full URI e.g., file:///...) of the photo in our case and apiUrl is the endpoint of the server-side.

我认为问题可能与formdata中uri的类型和格式有关.您是否尝试过使用图像选择器返回的uri?

I think the issue might be with the type and format of uri in formdata. Have you tried to use the uri returned by the image picker?

这篇关于在React Native(Expo)中上传图片,使用抓取会导致400错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆