[英]How to get file name from download link in firebase storage(Javascript, React)?
[英]how to download an image from firebase storage then reupload it but with different name using JavaScript
// Create a reference with an initial file path and name
const pathReference = sRef(st, 'RealTime_Recipes_Images/' + localStorage.getItem("rec_title_val") + '.png');
var blob;
getDownloadURL(pathReference)
.then((url) => {
console.log(url);
// This can be downloaded directly:
const xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = (event) => {
blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
})
.catch((error) => {
// Handle any errors
});
// Create the file metadata
const metadata = {
contentType: 'image/png'
};
// Upload file and metadata
const storageRef = sRef(
st,
"RealTime_Recipes_Images/" + recipe_title_input.value + ".png"
);
// 'file' comes from the Blob or File API
uploadBytes(storageRef, blob, metadata).then((snapshot) => {
console.log('Uploaded a blob or file!');
});
調試控制台 output:
https://firebasestorage.googleapis.com/v0/b/my-chef-7e1e8.appspot.com/o/RealTime_Recipes_Images%2Ftitle.png?alt=media&token=f4c8f00b-59d6-4f9f-ba3f-9a18e4086ebf
Uploaded a blob or file!
所以 url 成功返回,上傳部分運行良好,因為新上傳的圖像出現在存儲中,但我認為它是一個空 blob,因為 XMLHttpRequest() 不起作用,所以我能做些什么。 先感謝您
嘗試這個:
getDownloadURL(pathReference).then((url) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
var blob = e.currentTarget.response;
var content = e.currentTarget.getResponseHeader('Content-Disposition');
var fileName = content.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)[1];
savefile(blob, fileName);
}
xhr.send();
})
並編寫一個名為savefile
的 function (在外部),如下所示:
savefile(blob, fileName) {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = fileName;
a.dispatchEvent(new MouseEvent('click'));
}
希望這對你有幫助!
Firebase SDK now has a getBlob()
function that you can use to download a file directly instead of getting an URL first. 這也可以防止用戶與他人共享任何 URL。
import { storage } from '../path/to/firebase' // where firebase is initialized
import { getBlob, ref } from 'firebase/storage'
const storageRef = ref(storage, 'file/path.png')
const blob = await getBlob(storageRef)
const url = URL.createObjectURL(blob)
window.open(url)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.