1

Using JavaScript I need to download a binary file in the background, then modify such binary data (some internal processing) and at the end to offer a client to save such file to a local drive.

Please advise what kind of approach should I use.

000
  • 26,951
  • 10
  • 71
  • 101
Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • 1
    Serverside code, as you need to set the content disposition to get the file download dialog. – adeneo Jun 16 '13 at 20:47

1 Answers1

2

If you want to process the data at client-side you can Base64 encode your data at the end and construct an A-element and provide a data-uri with MIME-type set for the href attribute.

To download the data you can use AJAX (either with jQuery or directly if jQuery is not an option). Showing jQuery example here:

$.ajax({
    url: "pageThatProvidesBinaryData.html",
    context: document.body
}).done(function(data) {
    processData(data);
});

(be aware of encodings when you deal with binary data).

Process the data, then you can use (html5):

<a href="data:my/mime;charset=uft-8;base64,<your-data>" download="Filename.ext">
Click to download</a>

Replace my/mime to actual types (ie. application/octet-stream for generic binaries).

Providing a download attribute for the A-tag will allow the user to download the data when link is clicked (if he uses a html5 enabled browser).

If you want this to happen automatically, you can hide the a-element and generate a click:
Is it possible to trigger a link's (or any element's) click event through JavaScript?

For details on data-uris:
https://en.wikipedia.org/wiki/Data_URI_scheme

Community
  • 1
  • 1
  • That seems to solve the end part of my task, when I will dynamically generate an A link and simulate a click on it... But how should I download the data before that to do an internal processing? – Ωmega Jun 16 '13 at 21:06
  • @Ωmega You can download data asynchronous in the background using either AJAX or WebSockets. For this use jQuery and Ajax is probably the best choice. –  Jun 16 '13 at 21:20
  • @Ωmega Updated answer with example –  Jun 16 '13 at 21:29