react-native-fetch-blob阻止firebase调用n react native app

时间:2018-01-11 20:10:08

标签: firebase react-native blob image-upload react-native-fetch-blob

我有一个使用Firebase,firestore的本机应用程序。 为了上传图像,我正在使用“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的响应(不是catch / nothing =>只是传递thrue代码)。

如果我删除了这一行我可以读/写到firestore,bat我无法上传图片。

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

Heare是我的页面:

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)
        })
};

2 个答案:

答案 0 :(得分:3)

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

Trick仅在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)
        })
};

答案 1 :(得分:-1)

那么简单,您可以尝试上传图片

`try{
 {
    saltCmd = "\"salt -E \"($target)\" service.stop alip-di1 \
    result = salt authtype: 'pam', 
        clientInterface: local(
            arguments: saltCmd, 
            blockbuild: true, 
            function: 'cmd.run', 
            target: "lap1",
            saveFile: true,
            targettype: 'glob'),
        credentialsId: 'saltapi', 
        servername: 'http://salt:8000'
    }
}catch(e){
    result = e.toString()
    currentBuild.result = 'FAILURE'
}finally{
    echo result.replace("\\n",'\n')
}
}`