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

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

问题描述

我几天来一直在为图片上传而苦苦挣扎.我正在使用这样的表单数据:

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`,
});

uri 在 iOS 上类似于 asset-library://asset/path 在 Android 上类似于 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)

我尝试了所有将图像读取为 blob、删除内容类型、其他库(如 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) 中上传图片,使用 fetch 导致 400 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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