1

I'm making a POST call to my server with response type arraybuffer and it is currently returning a PDF blob with the following headers:

"Content-Type": "application/pdf"
"Content-Transfer-Encoding": "binary"
"Content-Disposition": "attachment;filename=file.pdf\"

I then create a blob url from the response:

var url = URL.createObjectURL(blob);

Is there any way to trigger a file download for this blob that works cross browser? I want the standard file download to occur as if the user had clicked on a link such as <a href="/file.pdf"></a>.

I've tried:

  • Using the url as the SRC for a script tag and it gets the blob, but no download
  • Using it as the url for an iFrame
  • Using it as the data url for object and embed tags, but it displays the object instead of downloading it
Bill
  • 25,119
  • 8
  • 94
  • 125
  • I think this solves your problem, at least in Chrome: http://stackoverflow.com/questions/6468517/force-download-of-datatext-plain-url – flamingcow Jun 10 '14 at 18:40
  • This requires the user to click on a second link and doesn't work in IE, so this doesn't solve my problem unfortunately. – Bill Jun 10 '14 at 19:01

1 Answers1

1

This is how I ended up solving the problem. I create a new form with the data needed to generate the document, set the target of the form to an iframe I create, and then submit the form. This causes the file to be downloaded correctly. I then just ended up using a cookie set by the server to determine when the download has completed.

var token = "my-form";

var form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('target', token);
form.setAttribute('action', "/my_target_url");

var hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', 'data');
hiddenField.setAttribute('value', JSON.stringify(data_to_submit));
form.appendChild(hiddenField);
element.append(form);

var frame = document.createElement('iframe');
frame.setAttribute('id', token);
frame.setAttribute('name', token);
frame.setAttribute('src', '');
frame.setAttribute('style', 'width:0;height:0;border:0px solid #fff;');
element.append(frame);

form.submit();
Bill
  • 25,119
  • 8
  • 94
  • 125