问题
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