React Native create blob from arbitrary data

帅比萌擦擦* 提交于 2021-02-10 05:42:13

问题


I have a React Native (0.59) app which consumes an (Swagger-generated) SDK that accepts Blob objects for file uploads. While there are sources on creating blobs from remote resources (e.g. using fetch), I couldn't find any resource on creating a blob on the fly. For example I have a string (regular JS string), and I need to upload that string as a text file to the server. I'll also have other file references from the file system where I'll also need to upload too.

How do I create Blob from any kind of arbitrary data in React Native?


回答1:


Have you tried the rn-fetch-blob package in react-native? I used this package for uploading image with the firebase as follows, it might help you.

import { firebase } from '../config';
import { Platform } from 'react-native';
import RNFetchBlob from 'react-native-fetch-blob';

const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;

window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;

export const uploadImage = (uri, mime, uid) => {
  return new Promise((resolve, reject) => {
    const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;

    let uploadBlob = null;

    const imageRef = firebase
      .storage()
      .ref('profileImg')
      .child(uid);
    fs.readFile(uploadUri, 'base64')
      .then(data => {
        return Blob.build(data, { type: `${mime};BASE64` });
      })
      .then(blob => {
        uploadBlob = blob;
        return imageRef.put(uploadUri, { contentType: mime });
      })
      .then(() => {
        uploadBlob.close();
        return imageRef.getDownloadURL();
      })
      .then(url => {
        resolve(url);
      })
      .catch(error => {
        reject(error);
      });
  });
};


来源:https://stackoverflow.com/questions/57314070/react-native-create-blob-from-arbitrary-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!