React Native create blob from arbitrary data
Asked Answered
P

1

5

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?

Phrixus answered 1/8, 2019 at 17:19 Comment(0)
C
10

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);
      });
  });
};
Cristincristina answered 6/8, 2019 at 5:49 Comment(4)
What React Native and RNFetchBlob versions are you using? There is no method named Blob.build in mine. The Blob methods are close, getRNFetchBlobRef, markAsDerived, onCreated, readBlob, and slice.Quillet
@CanPoyrazoğlu It is old one, Can I see your code? Actually you could just send your image to your server as base64 with proper content type or you could use this package pick image from gallery and get the base64 then send post request to your server with the data.Cristincristina
I'm using an external library (created internally by the company that I work with) which accepts a Blob, so those options are unfortunately not possible.Quillet
Oh, after further investigation I've found out that Blob.build is actually there, it's just IntelliSense that wasn't aware of it. It highlights my code complaining about Blob.build not existing, but it works at runtime.Quillet

© 2022 - 2024 — McMap. All rights reserved.