2017-02-14 54 views
0

我有我的組件狀態的兩個圖像路徑圖片上傳到火力在陣營本地

enter image description here

我嘗試上載功能,裏面的圖片之一,但得到一個錯誤:

Firebase Storage: Invalid argument in 'put' at index 0: Expected Blob or file 

和我的功能

submitImages =() => { 

    // Upload images to Firebase storage 
    let user = firebaseAuth.currentUser; 
    let imagesRef = storageRef.child('productImages/' + user.uid); 
    imagesRef.put(this.state.imageFront).then(snapshot => { 
     console.log('Uploaded ' + this.state.imageFront); 
    }); 
} 

我應該做的,而不是將這些圖片提供給Firebase。謝謝!

回答

3

錯誤說的是你需要使用一個blob。您可以使用反應原生取二進制大對象:https://github.com/wkh237/react-native-fetch-blob

看看這個例子:https://github.com/dailydrip/react-native-firebase-storage/blob/master/src/App.js#L43-L69

+0

謝謝!這個例子超級有用! –

+1

嘿,blob在EXPO中不起作用。有沒有其他方法? – chazefate

+0

沒有用EXPO這可能是唯一的方法嗎?我認爲世博會在這方面是有限的。想知道他們是否有一些圖書館來幫助我們。如果沒有,只是不使用它。 –

0

我張貼我的代碼,因爲這對我來說有點沮喪:

上傳圖片到火力地堡。存儲需要將圖像上傳爲Blob。如果你不知道什麼是斑點,不要擔心。

步驟1.

npm install --save react-native-fetch-blob

步驟2.

// copy and paste this code where you will handle the file upload 

import RNFetchBlob from 'react-native-fetch-blob' 

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

步驟3.

// The uploadImage function that you are going to use: 

function uploadImage(uri, mime = 'image/jpeg', name) { 

    return new Promise((resolve, reject) => { 
    let imgUri = uri; let uploadBlob = null; 
    const uploadUri = Platform.OS === 'ios' ? imgUri.replace('file://', '') : imgUri; 
    const { currentUser } = firebase.auth(); 
    const imageRef = firebase.storage().ref(`/jobs/${currentUser.uid}`) 

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

那麼,你如何調用這個函數? 將圖像的URI作爲第一個參數傳遞,作爲第二個參數,您可以傳遞'image/jpeg',最後一個參數是圖像的名稱。選擇你喜歡的名字。

但沃爾特我有幾個圖像,並希望上傳它們,並希望正確處理上傳。如果一個上傳成功而另一個不成功呢?

這樣做,那麼:

let imgPromises = []; 
imgPromises.push(uploadImage(img1, 'image/jpeg', 'imageOne')); 
imgPromises.push(uploadImage(img2, 'image/jpeg', 'imageTwo')); 
imgPromises.push(uploadImage(img3, 'image/jpeg', 'imageOne')); 

Promise.all(imgPromises).then(urls => { 
    // ALL IMAGES SUCCEEDED and you will get an array of URIS that you can save to your database for later use! 
}).catch(error => { 
    // One OR many images failed the upload. Give feedback to someone. 
})