Downloading files from Ajax POST Requests

Occasionally I stumble upon the need to download files from POST requests. An example would be generating PDF files, where the PDF content is dependent on the request. Interestingly this is not as straightforward as you may think, but it’s not that hard either.

A simple server

We’re going to implement a really simple
server which is generating PDFs from the POST request:

    $pdf->Cell(40,10, $pdfContent);
    return $pdf->Output(null, 'foobar-' . time() . '.pdf');

// Bad method

: This code uses the FPDF
library to generate PDF files. For demonstration purposes the pdf is filled with the content from $_POST['content']

FPDF automatically takes care about setting the Content-Disposition
to attachment
. In case you don’t use FPDF and need to set it manually simply add this before the output:

header('Content-Disposition: attachment; filename="filename.ext"');

Download the file

The more interesting thing about this is how the file is downloaded after sending the HTTP request. Let’s dive straight into it:

  Download POST Request

Enter a text and click the button: 

  document.getElementById('download').addEventListener('click', function () {
    var content = document.getElementById('content').value;
    var request = new XMLHttpRequest();'POST', '../server/', true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.responseType = 'blob';

    request.onload = function() {
      // Only handle status code 200
      if(request.status === 200) {
        // Try to find out the filename from the content disposition `filename` value
        var disposition = request.getResponseHeader('content-disposition');
        var matches = /"([^"]*)"/.exec(disposition);
        var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');

        // The actual download
        var blob = new Blob([request.response], { type: 'application/pdf' });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob); = filename;


      // some error handling should be done here...

    request.send('content=' + content);

Inhales deeply…

The actual download is done by creating a

object, which is used for a newly created a
tag with a link to the created Blob
object which is automatically clicked which ultimately opens the “Save file” dialog. Additionally it’s appended to the body
(which is a fix for Firefox) and is removed from the body afterwards (we don’t want to have tons of invisible a
tags on our body).

Well, as easy as vertically centering content in divs
! ( Flexbox is cheating!

Keep in mind that this implementation uses plain JavaScript (to make it easier for everybody to follow the example), but the actual download works the same for most frameworks (jQuery, Vue, Angular, …).

And, of course, you can find the entire implementation for this on GitHub

稿源 (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Downloading files from Ajax POST Requests

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录