我正在使用 api 來檢索 .png 檔案。當我嘗試為它創建一個 URL 以便我可以在我的 HTML 中顯示它時,呼叫失敗并顯示以下錯誤:
userCodeAppPanel:94 未捕獲的型別錯誤:無法在“URL”上執行“createObjectURL”:多載決議失敗。
我正在使用此代碼呼叫我的 api(使用 Google Apps 腳本):
function retrieveAdmiraltyTideGraph(tideStationName, dateFrom, numDays){
//get tide station code from tide station name passed from user input
let tideStationCode = getTideStationCode(tideStationName)
var url = _admiraltyURL "Stations/" tideStationCode "/TidalHeightGraph?dateTime=" dateFrom "&duration=" numDays;
url = url "&width=500&height=200"
var response = UrlFetchApp.fetch(url, _admiraltyRequestHeader);
var responseCode = response.getResponseCode()
var blob = response.getBlob()
Logger.log("graph response" responseCode)
Logger.log(blob.getContentType())
return blob
}
api 呼叫成功,因為記錄器顯示了正確的回傳代碼,對 blob 內容型別的檢查顯示它如預期的那樣是“image/png”。
我使用以下方法從 Java Script 呼叫 api 函式:
google.script.run.withSuccessHandler(showGraph).withFailureHandler(onFailure).retrieveAdmiraltyTideGraph(selectedStation, dateFrom, numDays);
顯示檢索到的影像的函式呼叫是:
function showGraph(blob){
var url = window.URL.createObjectURL(blob);
document.getElementById("graph").src = url
}
當我嘗試獲取 url 時,這是失敗的。
我對 JS 和 Google Apps 腳本很陌生,所以我可能會遇到一些簡單的錯誤,但我有非常相似的函式,它們在 api 處理程式、服務器代碼和客戶端代碼之間傳遞和處理陣列。
有什么建議?
謝謝
uj5u.com熱心網友回復:
改裝要點:
- 在您的 Google Apps Script 端,blob 回傳到 Javascript 端。遺憾的是,現階段還不能直接在Javascript端使用Google Apps Script的blob。我認為這可能是您的問題的原因。
在你的情況下,下面的修改如何?
修改后的腳本:
Google Apps 腳本方面:
從:
return blob
到:
return `data:${blob.getContentType()};base64,${Utilities.base64Encode(blob.getBytes())}`;
HTML&Javascript 端:
從:
function showGraph(blob){
var url = window.URL.createObjectURL(blob);
document.getElementById("graph").src = url
}
到:
function showGraph(url){
document.getElementById("graph").src = url
}
- 在此修改中,它假設標簽 like
<img id="graph">存在于您的 HTML 中。請注意這一點。
參考:
- base64Encode(資料)
添加:
從graph的document.getElementById("graph"),我還以為你可能想顯示影像。但是,如果你想讓用戶從 Google Apps Script 下載檔案,下面的修改如何?
修改后的腳本:
Google Apps 腳本方面:
從:
return blob
到:
return [`data:${blob.getContentType()};base64,${Utilities.base64Encode(blob.getBytes())}`, blob.getName()];
HTML&Javascript 端:
<input type="button" value="download" onclick="sample()">
<script>
function sample() {
google.script.run.withSuccessHandler(showGraph).withFailureHandler(onFailure).retrieveAdmiraltyTideGraph(selectedStation, dateFrom, numDays);
}
function showGraph([url, filename]){
fetch(url)
.then(res => res.blob())
.then(blob => {
var a = document.createElement("a");
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
});
}
function onFailure(e) {
console.log(e)
}
- 在此修改中,當單擊按鈕時,通過從 Google Apps 腳本檢索資料來下載檔案。
- 在這種情況下,請
selectedStation, dateFrom, numDays在 Javascript 端設定變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/394364.html
