3

我有一个使用 Firebase、firestore 的 react 本机应用程序。为了上传图片,我使用“react-native-fetch-blob”来创建一个 Blob。

在我用来上传文件的 js 文件中,我的代码如下所示:

const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob

**

window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest

**

由于这个window.XMLHttpRequest我的应用程序被阻止并且没有从 firebase 得到任何响应(不捕获 / 没有 => 只是通过代码)。

如果我删除了这一行,我可以读/写到 Firestore,蝙蝠我无法上传图像。

我可以做些什么来上传图像并继续写信到firestore?

这是我的页面:

import ImagePicker from 'react-native-image-crop-picker';
import RNFetchBlob from 'react-native-fetch-blob'
import firebase from 'firebase';

const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob

export const choozFile = (isSmalImg) => {
    let options = {
        width: isSmalImg ? 100 : 690,
        height: isSmalImg ? 100 : 390,
        cropping: true,
        mediaType: 'photo'
    };
    return new Promise((resolve, reject) => {
        ImagePicker.openPicker(options).then(response => {
            let source = { uri: response.path };
            resolve({ avatarSource: source, isProfileImg: isSmalImg })
        })
    });
}

export const addReportToFirebase = (obj = {}, uri, isProfile, mime = 'application/octet-stream') => {
    obj["uId"] = "JtXNfy34BNRfCoRO6luwhIJke0l2";
    const storage = firebase.storage();
    const db = firebase.firestore();
    const uploadUri = uri;
    const sessionId = new Date().getTime();
    let uploadBlob = null;

    const imageRef = storage.ref(`images${isProfile ? '/profile' : ''}`).child(`${sessionId}`)

    fs.readFile(uploadUri, 'base64')
        .then((data) => {
            return Blob.build(data, { type: `${mime};BASE64` })
        })
        .then((blob) => {
            uploadBlob = blob
            return imageRef.put(blob, { contentType: mime })
        })
        .then(() => {
            uploadBlob.close()
             imageRef.getDownloadURL().then((url)=>{
                obj['image'] = url;
                db.collection("reports").add(obj).then(() => {
                    console.log("Document successfully written!");
                }).catch((err) => {
                    console.error("Error writing document: ", err);                    
                });
            })
        })
        .catch((error) => {
            console.log('upload Image error: ', error)
        })
};
4

2 回答 2

6

我有同样的问题,我做了一些技巧来解决这个问题。这可能不是最正确的解决方案,但它对我有用。

技巧仅RNFetchBlob.polyfill.XMLHttpRequest用于window.XMLHttpRequest上传操作。完成将图像上传到存储后,将恢复window.XMLHttpRequest为原始值。

您的代码将如下所示。

    import ImagePicker from 'react-native-image-crop-picker';
import RNFetchBlob from 'react-native-fetch-blob'
import firebase from 'firebase';

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

window.Blob = Blob

export const choozFile = (isSmalImg) => {
    let options = {
        width: isSmalImg ? 100 : 690,
        height: isSmalImg ? 100 : 390,
        cropping: true,
        mediaType: 'photo'
    };
    return new Promise((resolve, reject) => {
        ImagePicker.openPicker(options).then(response => {
            let source = { uri: response.path };
            resolve({ avatarSource: source, isProfileImg: isSmalImg })
        })
    });
}

export const addReportToFirebase = (obj = {}, uri, isProfile, mime = 'application/octet-stream') => {
    obj["uId"] = "JtXNfy34BNRfCoRO6luwhIJke0l2";
    const storage = firebase.storage();
    const db = firebase.firestore();
    const uploadUri = uri;
    const sessionId = new Date().getTime();
    let uploadBlob = null;

    //keep reference to original value
    const originalXMLHttpRequest = window.XMLHttpRequest;

 window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
    const imageRef = storage.ref(`images${isProfile ? '/profile' : ''}`).child(`${sessionId}`)

    fs.readFile(uploadUri, 'base64')
        .then((data) => {
            return Blob.build(data, { type: `${mime};BASE64` })
        })
        .then((blob) => {
            uploadBlob = blob
            return imageRef.put(blob, { contentType: mime })
        })
        .then(() => {
            uploadBlob.close();

            //revert value to original
            window.XMLHttpRequest = originalXMLHttpRequest ;
             imageRef.getDownloadURL().then((url)=>{
                obj['image'] = url;
                db.collection("reports").add(obj).then(() => {
                    console.log("Document successfully written!");
                }).catch((err) => {
                    console.error("Error writing document: ", err);                    
                });
            })
        })
        .catch((error) => {
            console.log('upload Image error: ', error)
        })
};
于 2018-04-08T09:12:02.543 回答
-1

that simple,,u can try this to upload image

<i>
getSelectedImages = (selectedImages, currentImage)=>{
    const image = this.state.uri
    let uploadBlob = null
    let mime = 'image/jpg'
    const originalXMLHttpRequest = window.XMLHttpRequest;
    const originalBlob = window.Blob;
    window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
    window.Blob = RNFetchBlob.polyfill.Blob
    const imageRef = firebase.storage().ref('posts').child(this.state.uri)
    RNFetchBlob.fs.readFile(image, 'base64')
      .then((data) => {
        return Blob.build(data, { type: `${mime};BASE64` })
    })
    .then((blob) => {
        uploadBlob = blob
        return imageRef.put(blob, { contentType: mime })
      })
      .then(() => {
        uploadBlob.close()
        window.XMLHttpRequest = originalXMLHttpRequest ;
        window.Blob = originalBlob
        return imageRef.getDownloadURL()
      })
      .then((url) => {
        firebase.database().ref('groub').child(params.chat).child('message').push({
          createdAt:firebase.database.ServerValue.TIMESTAMP,
          image:url,
          user:{
            _id:params.id,
            name:params.name,
          },
        })
        alert('Upload Sukses') 
      })
      .catch((error) => {
        console.log(error);
      })  
 
  }

</i>

于 2018-10-16T10:07:14.900 回答