Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set content-disposition = attachment via javascript?

How can I set content-disposition = attachment via javascript?

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

How can I do this ?

like image 982
Prakash Raman Avatar asked Oct 20 '10 07:10

Prakash Raman


People also ask

What is content disposition Javascript?

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.

How do you use content disposition inline?

Working of Content Disposition and Multipart : On using inline disposition, the multipart should be displayed normally and if any attachment sub-part is present, it requires user action. User action is required when attachment disposition is used as whole on multipart.

What is content disposition attachment filename?

Content-Disposition is an optional header and allows the sender to indicate a default archival disposition; a filename. The optional "filename" parameter provides for this. This header field definition is based almost verbatim on Experimental RFC 1806 by R. Troost and S.

What is content disposition inline?

The Content-Disposition HTTP Header response header is a header that indicates whether the content will be displayed inline in the browser. It is a web page or as part of a web page, or as an attachment that will be downloaded and saved locally.


2 Answers

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

like image 52
nnevala Avatar answered Sep 28 '22 18:09

nnevala


Firefox and Chromium-based browsers support the download attribute. If you need better compatibility now, use the Flash-based Downloadify as a fallback.


HTML only: use the download attribute:

<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:

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);
like image 20
fregante Avatar answered Sep 28 '22 18:09

fregante