如何将 React Native 图像 uri 转换为二进制文件

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

我正在使用 expo-image-picker 从设备中选取图像,但它返回图像 uri。我想将该图像作为二进制文件发送到我的 api。图像 uri 在后端对我不起作用。谁能帮帮我,我已经被这个问题困扰好几天了。

react-native expo
2个回答
0
投票

这已经晚了,但是对于任何偶然发现这一点的人来说,这对我有用:

const uploadFile = async (uri, extension) => {
const formData = new FormData();
const uriParts = uri.split(".");
const fileType = uriParts[uriParts.length - 1];
const type = extension ? "movi" : "image";
const file = {
  uri,
  name: `FILE-${new Date().getTime()}.${extension ?? "jpg"}`,
  type: `${type}/${fileType}`,
};

formData.append("image", file as any);
const response = await apiInstance.post("/upload", formData, {
  headers: {
    "Content-Type": "multipart/form-data",
  },
});
return response.data.image;

};


-1
投票

有两种方法可以解决这个问题:

1。将

base64
设置为
true
以启动媒体库方法选项

let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    allowsEditing: true,
    aspect: [4, 4],
    quality: 1,
    base64:true
  });

然后上传图片base64数据

2。获取图像二进制数据,最好是 BLOB 格式。


const blob = await new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest();
  xhr.onload = function () {
    resolve(xhr.response);
  };
  xhr.onerror = function (e) {
    reject(new TypeError("Network request failed"));
  };
  xhr.responseType = "blob";
  xhr.open("GET", [PATH_TO_LOCAL_FILE_HERE], true);
  xhr.send(null);
});

// Your logic to upload `blob` to a backend server or cloud provider

// We're done with the blob, close and release it
blob.close();
© www.soinside.com 2019 - 2024. All rights reserved.