拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 无法运行window.URL.createObjectURL(blob)以显示.png档案

无法运行window.URL.createObjectURL(blob)以显示.png档案

白鹭 - 2022-02-16 1984 0 0

我正在使用 api 来检索 .png 档案。当我尝试为它创建一个 URL 以便我可以在我的 HTML 中显示它时,呼叫失败并显示以下错误:

我正在使用此代码呼叫我的 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(资料)

添加:

graphdocument.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 端设定变量
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *