【问题标题】:Open or save a file after downloading in angular以角度下载后打开或保存文件
【发布时间】:2018-12-08 14:40:33
【问题描述】:

我有一个用例,如果文件可以在新选项卡中打开,它应该在新选项卡中打开。如果没有,它会以给定的名称保存(名称应该是动态设置的)。

我目前有以下sn-p:

         if (windowService.navigator.msSaveOrOpenBlob) {
             windowService.navigator.msSaveOrOpenBlob(file, fileName);
         } else {
             const link: HTMLAnchorElement = document.createElement("a") as HTMLAnchorElement;
             link.href = windowService.URL.createObjectURL(file);
             if (fileName) {
                 link.download = fileName;
             }
             link.target = "_blank";
             document.body.appendChild(link);
             link.click();
             document.body.removeChild(link);
         }

当我使用它时,所有文件都会被下载(包括 pdf/text,否则在尝试使用 window.open() 时会在新选项卡中打开)。 我的要求是:如果文件可以在新标签中打开,它们应该在新标签中打开(例如 pdf/text 等(在尝试使用 window.open() 时会在新标签中打开) .)。 我知道我可以使用 window.open() 但这不支持将 desired name 设置为文件。

有没有办法做到这一点? 另外,在下载之前如何确定文件是否可以在新选项卡中打开?如果我知道文件无法打开,在这种情况下我会下载,否则我会在新选项卡中打开它。

【问题讨论】:

    标签: javascript angular window


    【解决方案1】:

    我们使用解决的相同要求:

    1. 客户端html中的标准<a/>标签,使浏览器能够以标准方式处理它们
    2. 更改 webservice,因此它通过设置 Content-Disposition 返回文件 标头inline;

    不幸的是,尝试调整 window.opencreateObjectURL 以显示文件的正确名称...被证明是徒劳的。

    控制器:

    路由:server/download/{guid}

    var contentDisposition = new ContentDispositionHeaderValue(DispositionTypeNames.Inline);
    contentDisposition.SetHttpFileName(document.Name);
    Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
    

    component.html:

    <a [class]="'document-link'"
    [href]="docUrl(document.id)"
    target="_blank"
    title="{{document.name}}">{{document.name}}
    </a>
    

    Component.ts

    docUrl(id) 函数只是构造正确的 url 到控制器。

    docUrl(guid:string){
      return this.fileService.url+'/download/'+guid;
    }
    

    【讨论】:

      【解决方案2】:

      要强制下载,您需要在响应标头中设置 Content-Disposition 标头

      打开文件或下载取决于。例如打开 PDF,如果您的浏览器支持 PDF 查看器,它会打开,否则会自动下载

      【讨论】:

      • 是的,我的浏览器确实支持打开 pdf,但上面的代码会导致下载文件,而不是打开新标签页。当我尝试 window.ope(link.href) 时,pdf 会在新选项卡中以随机名称打开。
      • @LotsOfQuestions 是的,打开时没有文件名。如果您需要,您必须使 url 直接从具有文件名的服务器提供服务。例如。 ~/sample.pdf 将打开或下载名为 sample.pdf 的文件
      • 是的,但是如果文件无法在新选项卡中打开,它应该以函数指定的名称保存(Chrome 分配一个随机名称)。
      • @SanthoshS 如果我发送带有标题、上传者名称等其他数据的 JSON 响应,我如何发送内容处置标头?
      【解决方案3】:

      下载或保存后打开文件。

      /**
       * Method is use to download file.
       * @param data - Array Buffer data
       * @param type - type of the document.
       */
      downLoadFile(data: any, type: string) {
          var blob = new Blob([data], { type: type.toString() });
          var url = window.URL.createObjectURL(blob);
          window.open(url);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多