【问题标题】:Converting Base64 string into blob in React Native在 React Native 中将 Base64 字符串转换为 blob
【发布时间】:2021-01-28 17:16:16
【问题描述】:

我一直在寻找将图像从 base64 字符串转换为 Blob 的解决方案

我通过 react-native-image-crop-picker 获取图像

我得到的图像对象是这样格式化的:

{ 
creationDate: "1299975445"
cropRect: null
data: "/9j...AA"
duration: null
exif: null
filename: "IMG_0001.JPG"
height: 2848
localIdentifier: "10...001"
mime: "image/jpeg"
modificationDate: "1441224147"
path: "/Users/...351F66445.jpg"
size: 1896240
sourceURL: "file:///Users/...IMG_0001.JPG"
width: 4288
}

这意味着我将路径和源 url 和图像数据作为 base64 字符串。

我需要将用户选择为 blob 文件的图像上传到服务器。

那么有什么方法可以在 react native 中进行转换。

ps:我已经尝试了我在网上找到的解决方案,但到目前为止似乎没有一个有效,但似乎没有一个对我有效。

urlToBlob = (url) => new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onerror = reject;
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        resolve(xhr.response);
      }
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob'; // convert type
    xhr.send();
  })



this.urlToBlob(data)
        .then((blob) => {
          console.log(blob);
        });

我尝试了这种和平的代码,这就是我在控制台中得到的:

{
_data:
blobId: "B69744A5-B8D7-4E6B-8D15-1C95069737EA"
name: "Unknown"
offset: 0
size: 1896240
type: "image/jpeg"
__collector: null
}

【问题讨论】:

    标签: react-native


    【解决方案1】:

    经过大量搜索,如果有人遇到此问题,我找到了解决方案。 我使用了一个“提取文件”包,它允许我将图像作为文件发送到服务器 它是这样工作的:

    import { ReactNativeFile } from 'extract-files';
    const FormData = require('form-data');
    
    _addImage = async () => {
    const { images } = this.state;
    
    if (images.imageData.length > 0) {
      const formData = new FormData();
    
    
    // converting images to files 
      images.imageData.forEach((element) => {
        const file = new ReactNativeFile({
          uri: element.sourceURL,
          name: element.filename,
          type: element.mime,
        });
        formData.append('files', file);
      });
    
    // sending files to the server
      await addImages(formData).then((response) => {
        console.log('response : ', response);
        if (response.success) {
          this.pictures = response.filesNames;
          this.setState({
            isLoading: true,
            pictures: response.filesNames
          });
          return response.success;
        }
      }).catch((err) => {
        console.error(err);
      });
    }
      }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2019-10-03
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 2015-12-20
      • 2015-04-22
      • 2015-01-31
      • 2020-03-28
      相关资源
      最近更新 更多