Javascript 如何通过javascript设置内容处置=附件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3975648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:57:58  来源:igfitidea点击:

how to set content-disposition = attachment via javascript?

javascripthtmlhttp-headers

提问by Prakash Raman

How can I set content-disposition = attachmentvia javascript?

如何content-disposition = attachment通过javascript进行设置?

Basically, I would like to force a "SaveAs" operation after a page has loaded via Javascript, using Firefox.

基本上,我想在使用 Firefox 通过 Javascript 加载页面后强制执行“另存为”操作。

How can I do this ?

我怎样才能做到这一点 ?

回答by nnevala

Content-Disposition is a response header, ie. the server must return it. You can't achieve this with client-side javascript.

Content-Disposition 是一个响应头,即。服务器必须返回它。您无法使用客户端 javascript 实现此目的。

回答by fregante

Firefox and Chromium-based browsers support the downloadattribute. If you need better compatibility now, use the Flash-based Downloadifyas a fallback.

Firefox 和基于 Chromium 的浏览器支持download属性. 如果您现在需要更好的兼容性,请使用基于 Flash 的Downloadify作为后备。



HTML only:use the downloadattribute:

仅 HTML:使用download属性:

<a download href="http://upload.wikimedia.org/wikipedia/commons/b/bb/Wikipedia_wordmark.svg">Download</a>



Javascript only:you can save any file with this code:

仅 Javascript:您可以使用以下代码保存任何文件:

function saveAs(uri) {
    var link = document.createElement('a');
    if (typeof link.download === 'string') {
        link.href = uri;
        link.setAttribute('download', true);

        //Firefox requires the link to be in the body
        document.body.appendChild(link);

        //simulate click
        link.click();

        //remove the link when done
        document.body.removeChild(link);
    } else {
        window.open(uri);
    }
}

var file = 'http://upload.wikimedia.org/wikipedia/commons/b/bb/Wikipedia_wordmark.svg';
saveAs(file);

回答by abhishek kasana

1.Use Anchor "download"(HTML5) attribute

1.使用Anchor“下载”(HTML5)属性

<a href='abc.pdf' download>Click Here</a>

2.Create href programmatically using js,

2.使用js以编程方式创建href,

const link = document.createElement('a');
link.href = '/xyz/abc.pdf';
link.download = "file.pdf";
link.dispatchEvent(new MouseEvent('click'));

According to Mozilla doc Anchor element, download attribute(HTML5) instructs browsers to download a URL instead of navigating to it.

根据 Mozilla doc Anchor element,下载属性(HTML5)指示浏览器下载 URL 而不是导航到它。

Important Notes:

重要笔记:

  • This attribute only works for same-origin URLs.
  • Although HTTP(s) URLs need to be in the same-origin, blob: URLs and data: URLs are allowed so that content generated by JavaScript, such as pictures created in an image-editor Web app, can be downloaded.
  • 此属性仅适用于同源 URL。
  • 尽管 HTTP(s) URL 需要同源,但允许 blob: URL 和 data: URL,以便可以下载 JavaScript 生成的内容,例如在图像编辑器 Web 应用程序中创建的图片。

So the above js method to create anchor element dynamically and using it download the file will only work for the same origin files i.e There are two ways to handle this problem ->

因此,上述动态创建锚元素并使用它下载文件的js方法仅适用于相同来源的文件,即有两种方法可以处理此问题->

  • Client-side
  • Server-side
  • 客户端
  • 服务器端

Client-side solution:->

客户端解决方案:->

A work around for this problem, refrenced in second Note i.e a blob object can be used, with the help of fetch js API

解决此问题的方法,在第二个注解中提及,即可以在 fetch js API 的帮助下使用 blob 对象

url = 'https://aws.something/abc.pdf';

fetch(url, {
      method: 'GET',
    }).then(function(resp) {
      return resp.blob();
    }).then(function(blob) {
      const newBlob = new Blob([blob], { type: "application/pdf", charset: "UTF-8" })

      // IE doesn't allow using a blob object directly as link href
      // instead it is necessary to use msSaveOrOpenBlob
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(newBlob);
        return;
      }
      const data = window.URL.createObjectURL(newBlob);
      const link = document.createElement('a');
      link.dataType = "json";
      link.href = data;
      link.download = "file.pdf";
      link.dispatchEvent(new MouseEvent('click'));
      setTimeout(function () {
        // For Firefox it is necessary to delay revoking the ObjectURL
        window.URL.revokeObjectURL(data), 60
      });
    });

Server-side solution:->

服务器端解决方案:->

The other option is if you can control the server side response headers then this may be the best option.

另一种选择是,如果您可以控制服务器端响应标头,那么这可能是最佳选择。

In a regular HTTP response, the Content-Dispositionresponse header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally. e.g

在常规 HTTP 响应中,Content-Disposition响应标头是一个标头,指示内容是否应在浏览器中内联显示,即作为网页或网页的一部分,或作为附件,下载并保存到本地。例如

Content-Disposition: attachment
Content-Disposition: attachment; filename="filename.jpg"

For a file hosted on AWS , its response headers can be edited, these can be changed in meta data, add the content disposition header in the meta data in the file or the folder propertities, add key as content-disposition and value as attachment,

对于托管在 AWS 上的文件,可以编辑其响应标头,可以在元数据中更改这些标头,在文件或文件夹属性的元数据中添加内容处置标头,将键添加为内容处置,将值添加为附件,

content-disposition : attachment

Now whenever this file is hit from a browser it would always download instead of opening, now if u use this file link in a anchor tag it would be downloaded directly with use of download html tag.

现在,每当从浏览器点击此文件时,它总是会下载而不是打开,现在如果您在锚标签中使用此文件链接,它将使用下载 html 标签直接下载。