我有一個功能要求用戶從他們的手機中獲取影像。一旦給出,路徑就會上傳到 firebase,看起來像這樣:
file:///var/mobile/Containers/Data/Application/9C627709-0F0C-4A2A-939E-9206DA91032C/Library/Caches/ExponentExperienceData/%40user%2FAPP/ImagePicker/1B5D0907-8ED5-46DC-B216-7DEF7992C1BF.jpg"
問題在于,在嘗試顯示時,它僅顯示在已上傳此影像的手機上,因為其他設備不擁有此影像。
如何將 firebase 路徑/影像轉換為可在所有手機中顯示的影像,即使此影像在所有用戶設備上都不存在?
以下是一些重要的代碼:
獲取庫影像的函式
const addImage = async () => {
let image = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!image.cancelled) {
setGalleryImage(image.uri);
}
};
將影像添加到 firebase 的函式:
const createPhoto = async () => {
await db
.collection("data")
.doc(route?.params?.docId)
.set(
{
galleryImage,
}
)
.then(() => {
})
.catch(error => alert(error));
};
顯示影像的 Jsx:
<Image
source={{ uri: galleryImage }}
onl oadStart={() => setIsLoading(true)}
onl oadEnd={() => setIsLoading(false)}
/>
任何幫助表示贊賞
uj5u.com熱心網友回復:
這是因為,您正在保存影像的本地路徑,因此無法在其他手機上顯示。您需要將影像上傳到存盤桶并將該影像的 URL 保存在資料庫中。
將影像轉換為 blob
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(xhr.response);
};
xhr.onerror = function() {
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
// image.uri is the local path of the image on the device
xhr.open("GET", image.uri, true);
xhr.send(null);
})
上傳圖片到存盤
const storageRef = ref(storage, `profile-pictures/${userContext.user.uid}/${name}`);
const task = uploadBytesResumable(storageRef, blob)
task.on('state_changed', (snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
}, (err) => {
reject(err)
}, () => {
getDownloadURL(task.snapshot.ref)
.then((downloadURL) => {
// image successfully uploaded, save "downloadURL" in your db
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/512255.html
標籤:Google Cloud Collective javascript火力基地反应式
