1

I'm trying to download a binary file using XMLHttpRequest and store its content. The URL im querying returns the PDF data. This is how the request to the server and response looks like :

POST /download.php HTTP/1.1
[....]

id=1&file_type=pdf

HTTP/1.1 200 OK
Server: Apache
Content-Disposition: attachment; filename="file_1.pdf";filename*=ut8'en'file_1.pdf
X-Cnection: close
Content-Type: application/octet-stream
[.....]
Connection: keep-alive

%PDF-1.3
[raw PDF data]

I tried this code and i still get nothing but a blank response :

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://foo.example.com/download.php', true);
//xhr.overrideMimeType("text/plain; charset=x-user-defined");
//xhr.responseType = 'arraybuffer'; // blob too
xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 && xhr.status == 200){
                var file = xhr.response // this.response
                // store it somewhere ..
            }
        }
        xhr.send("id=1&file_type=pdf");
   }

Note : The request is sent from a page in : www.example.com

Is there any kind of trick to do it via XHR ? How would you achieve this yourself?

Any help or hint is much appreciated :)

  • I see that you have a full host name in the xhr open. if the host is not the same as your website, then you may be having a CORS issue ... check the developer tools console for errors – Jaromanda X Feb 09 '16 at 03:27
  • @JaromandaX The host is in the same origin – user2804788 Feb 09 '16 at 11:50
  • @JaromandaX Do u have any idea how to do it ? – user2804788 Feb 09 '16 at 11:53
  • @JaromandaX I tried it and i get an empty string, btw i edited the question to clarify more – user2804788 Feb 09 '16 at 12:25
  • *The host is in the same origin* ... no, it isn't - since the updated question states that the page is `www.example.com`, request for resource at `foo.example.com` ... it's a CORS issue as there are no CORS headers in the response ... Add `Access-Control-Allow-Origin: www.example.com` to the response headers in download.php on `foo.example.com` – Jaromanda X Feb 09 '16 at 12:27
  • @JaromandaX thanks, so to make it work i should add Access-Control-Allow-Origin header in response ? – user2804788 Feb 09 '16 at 12:31
  • indeed - and *check the developer tools console for errors* – Jaromanda X Feb 09 '16 at 12:32
  • @JaromandaX thanks for your clarification i was suspicious about that – user2804788 Feb 09 '16 at 12:40
  • Possible duplicate of [Access denied CORs request in IE10+ in angularjs with required Cross Origin Resource Sharing error (info?)](http://stackoverflow.com/questions/32206672/access-denied-cors-request-in-ie10-in-angularjs-with-required-cross-origin-reso) – Paul Sweatte Sep 14 '16 at 01:35

0 Answers0