我正在打一個簡單的window.location.href電話來開始檔案下載。之后,我呼叫一個方法來重新加載一個表。
window.location.href = url;
this.getFileListing();
但是重新加載太快了,因為 href 創建了一個資料庫記錄。
添加 1 秒超時修復它:
window.location.href = url;
setTimeout(() => {
this.getFileListing();
}, 1000);
……但這太草率了。在呼叫重新加載之前,如何等待下載開始(因此資料庫記錄將存在)?
*注意:視窗的位置不會改變。我只是使用 windows.location.href 來呼叫本地路由,該路由開始下載檔案。因此,我不相信 popstate 或 hashchange 會起作用。
uj5u.com熱心網友回復:
window.location.href您可以使用 axios 下載檔案并使用then承諾的方法來啟動所需的方法,而不是使用 for vue 啟動下載
axios({
url: url,
method: 'GET',
responseType: 'blob'
.then(response => (this.getFileListing()))
如果您使用的是 jQuery,則可以嘗試與 jquery 等效的方法 get https://api.jquery.com/jquery.get/
var instance = this;
$.get("fileToDownload", function() {
//code when download is launch
}).done(function() {
instance.getFileListing();
})
uj5u.com熱心網友回復:
我的解決方案:使用 axios 和大量代碼來獲取回應,并將其傳遞給瀏覽器。我不得不決議出原始檔案名。不確定是否值得。實際上,我將這些函式放在了一個 mixin 中,這樣我就可以輕松地將它添加到其他組件中。
downloadToBrowser(url, successCallback) {
axios({
method: 'GET',
url: url,
responseType: 'blob'
})
.then(response => {
this.startDownload(response);
successCallback();
});
},
startDownload(response) {
var filename = response.headers['content-disposition'].split('=')[1];
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
},
然后呼叫方法,傳入url和回呼:
this.downloadToBrowser(url, this.getFileListing);
*如果您對我可以做得更好/不同的事情有任何意見,我歡迎反饋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/419779.html
標籤:
上一篇:我正在嘗試發出AJAX獲取請求,但我不斷收到錯誤“UncaughtSyntaxError:Unexpectedtoken')'”
