简体   繁体   中英

Downloading file instead of opening in javascript

I use a function http://js.cytoscape.org/#cy.jpg to get the graph in jpg format.

I use it with window.location.assign(cy.jpg()); , but it opens the image opens in the same tab.

I want it to download instead of opening in the tab. I guess I have to set content-disposition = attachment or something like that.

Edit

I solved it with

const link = document.createElement('a');
link.download = 'filename.png';
link.href = cy.png();
link.click();

however, it is not compatible in all browsers.

You can set <a> element href attribute to result of cy.png() , set download attribute at <a> element, call click() on <a> element.

Alternatively, you can replace MIME type "image/png" portion of data URI returned by cy.png() with "application/octet-stream" , then set location.href to replacement data URI

  var url = cy.png();
  url = url.replace("image/png", "application/octet-stream");
  window.location.href = url;

See also How to download a file without using <a> element with download attribute or a server?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM