我張貼我的代碼,因爲這對我來說有點沮喪:
上傳圖片到火力地堡。存儲需要將圖像上傳爲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.
})
謝謝!這個例子超級有用! –
嘿,blob在EXPO中不起作用。有沒有其他方法? – chazefate
沒有用EXPO這可能是唯一的方法嗎?我認爲世博會在這方面是有限的。想知道他們是否有一些圖書館來幫助我們。如果沒有,只是不使用它。 –