简体   繁体   English

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

[英]how to set content-disposition = attachment via javascript?

How can I set content-disposition = attachment via javascript? 如何通过javascript设置content-disposition = attachment

Basically, I would like to force a "SaveAs" operation after a page has loaded via Javascript, using Firefox. 基本上,我想在使用Firefox通过Javascript加载页面后强制执行“SaveAs”操作。

How can I do this ? 我怎样才能做到这一点 ?

Content-Disposition is a response header , ie. Content-Disposition是一个响应头 ,即。 the server must return it. 服务器必须返回它。 You can't achieve this with client-side javascript. 您无法通过客户端javascript实现此目的。

Firefox and Chromium-based browsers support the download attribute . Firefox和基于Chromium的浏览器支持download属性 If you need better compatibility now , use the Flash-based Downloadify as a fallback. 如果您现在需要更好的兼容性,请使用基于Flash的Downloadify作为后备。


HTML only: use the download attribute: 仅限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); 

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元素 ,下载属性(HTML5)指示浏览器下载URL而不是导航到它。

Important Notes: 重要笔记:

  • This attribute only works for same-origin URLs. 此属性仅适用于同源URL。
  • 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. 虽然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 ie 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 ie 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-Disposition response 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. 在常规HTTP响应中, Content-Disposition响应标头是一个标头,指示内容是否应在浏览器中内嵌显示,即作为网页或作为网页的一部分显示,还是作为附件显示下载并保存在本地。 eg 例如

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. 现在无论何时从浏览器点击这个文件,它总是会下载而不是打开,现在如果你在锚标签中使用这个文件链接,它将直接使用download html标签下载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 beforeunload 事件和 Content-Disposition=attachment - beforeunload event and Content-Disposition=attachment 内容处置:附件未触发下载对话框 - Content-Disposition:attachment not triggering download dialog XMLHttpRequest 是否阻止了 Content-Disposition 附件? - Is Content-Disposition attachment blocked from XMLHttpRequest? 解压一个内容处理的 gzip 文件:附件 - Unpack a gzip file that is content-disposition: attachment 使用Javascript进行“内容处理”行为 - “Content-disposition”-like behavior with Javascript 如何与content-disposition:附件暂时停用onbeforeun-message? - How to temporally deactivate onbeforeunload-message in combination with content-disposition: attachment? 可以检测到 iframe 中的加载完成,内容处置:附件? - possible to detect loading complete in iframe with content-disposition: attachment? 如何纠正内容配置错误 - How to correct content-disposition error 通过PHP的标题下载文件后,将document.readyState的状态更改为“完成”(“ Content-Disposition:附件…” - changing state of document.readyState to “complete” after downloading file via PHP's header('Content-Disposition: attachment…' 设置“ Content-disposition”而不设置“ Content-Length”是否可以接受? - Is it acceptable to set 'Content-disposition' without 'Content-Length'?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM