[英]How to download a file from firebase storage automaticly and not with the url - Javascript
[英]How to download a file from firebase storage in a Vue web app?
情況:您需要通過具有 vue.js 網絡應用程序(包含 vuetify)的瀏覽器將 pdf 文件(或任何文件類型)從 firebase 存儲下載到您的計算機。 您已經查看了firebase storage doc ,但它不是很清楚。 您不確定適合您的 Firebase 存儲規則。 這是用於前端 - 用戶的瀏覽器。 你將如何實施?
這是關於如何通過 vue 網絡應用程序將文件從 firebase 存儲下載到用戶計算機的編譯答案。 firebase 存儲下載文檔包含 vue.js Web 應用程序將文件下載到計算機所需的 90%。 按照那里的步驟操作。 如果您沒有使用 firebase 身份驗證,那么您可能希望為所有人設置讀取訪問權限。 默認情況下,只有經過身份驗證的用戶才能讀寫。 您可以在 Firebase 存儲規則中這樣做:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read: if request.auth == null;
allow write: if request.auth != null;
}
}
}
這允許任何人查看/下載您的文件。 接下來,按照上面發布的指南,您將能夠獲取文件的 url,然后將其轉換為“blob”格式。 現在,該指南沒有告訴您接下來要做什么,但另一個Stack Overflow 答案有解決方案。 我在這里結合了兩者。 基本上代碼中發生的事情是:
@click.prevent
事件發射器而不是@click
調用事件處理函數。a
元素,然后將其href
屬性分配給“blob”、下載名稱並發出click
事件。 之后撤消href
屬性,以免發生意外。 傳統上,我們用a
鏈接來下載文件,但我們可以用v-btn
因為我們正在創建a
事件處理程序的鏈接。 我的按鈕有一個工具提示和圖標。 另外,由於 linter,我刪除了 unuses 變量。
<v-tooltip top>
<template v-slot:activator="{ on, attrs }">
<v-btn
:color="counterThemeColorClass"
fab
ripple
v-bind="attrs"
v-on="on"
@click.prevent="downloadResumePdf"
>
<v-icon
:color="themeColorClass"
x-large
>mdi-file-account-outline</v-icon>
</v-btn>
</template>
<span class="font-weight-bold">download resume</span>
</v-tooltip>
downloadResumePdf() {
const resumeRef = firebase.storage()
.ref('tenzin_resume.pdf');
resumeRef.getDownloadURL().then((url) => {
// `url` is the download URL
console.log(url);
// This can be downloaded directly:
const xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function () {
const blob = xhr.response;
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'tenzin_resume';
link.click();
URL.revokeObjectURL(link.href);
};
xhr.open('GET', url);
xhr.send();
}).catch((error) => {
// Handle any errors
switch (error.code) {
case 'storage/object-not-found':
// File doesn't exist
break;
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect the server response
break;
default:
break;
}
});
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.