React Native从任意数据创建Blob [英] React Native create blob from arbitrary data
问题描述
我有一个React Native(0.59)应用程序,它使用一个(由Swagger生成的)SDK,该SDK接受 Blob
对象进行文件上传.虽然有从远程资源创建blob的资源(例如,使用fetch),但我找不到在动态创建blob的任何资源.例如,我有一个字符串(常规JS字符串),我需要将该字符串作为文本文件上传到服务器.我还将从文件系统中获取其他文件引用,在这里也需要上传.
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.
如何在React Native中根据任意类型的数据创建Blob?
How do I create Blob from any kind of arbitrary data in React Native?
推荐答案
您是否在react-native中尝试过rn-fetch-blob软件包?我使用此程序包通过Firebase上传图像的方法如下,这可能会对您有所帮助.
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);
});
});
};
这篇关于React Native从任意数据创建Blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!