0

I'm making an ajax POST call to my server, generating an ugly remote download URL, passing that to nginx with proxy_pass and then serving the file to the client. See here for process. The image seems to make it to the client, I just can't get it to download.

As seen in screenshots, the chrome response preview shows the jpeg, the headers look good (content-disposition attachment).

How can I turn this response into a downloadable file for the user?

Response preview in chrome

Response headers

Logged response data

I've tried https://stackoverflow.com/a/23797348/5697126, however, the file that gets downloaded is corrupted and 150% size of the real image. Here's my attempt, it does download a file, but the file is corrupted with the message - Error interpreting JPEG image file (Not a JPEG file: starts with 0xef 0xbf)

const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
  const matches       = filenameRegex.exec(_responseHeaders['content-disposition']);
  let fileName        = '';
  if (matches != null && matches[1])
  {
    fileName = matches[1].replace(/['"]/g, '');
  }

  let fileType = _responseHeaders['content-type'];
  let blob     = new Blob([_response], {type: fileType});

  let URL         = window.URL || window.webkitURL;
  let downloadUrl = URL.createObjectURL(blob);

  if (fileName)
  {
    // use HTML5 a[download] attribute to specify filename
    let a = document.createElement('a');
    // safari doesn't support this yet
    if (typeof a.download === 'undefined')
    {
      window.location = downloadUrl;
    }
    else
    {
      a.href     = downloadUrl;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
    }
  }
  else
  {
    window.location = downloadUrl;
  }

  setTimeout(function ()
  {
    URL.revokeObjectURL(downloadUrl);
  }, 100); // cleanup
Micheal C Wallas
  • 495
  • 6
  • 14

1 Answers1

0

Solved!

I had to set the ajax (axios) response type to 'blob' as the default is json. See - https://github.com/axios/axios/issues/448

Once the response was blob, I just piped the _response to URL.createObjectURL and then rest of the code I posted worked like a charm

Micheal C Wallas
  • 495
  • 6
  • 14