Reputation: 2053
I am sending a post request to a rest service to get a content. The content can be any of the types. (pdf, doc, pptx, docx, img, png, mp3, etc)
I have a very simple html and javascript to load the the content.
html
<html>
<head>
<script type="text/javascript" src="test.js"></script>
click
</head>
<body>
<button type="submit" target='_blank' onclick="Test()">Test</button>
</body>
</html>
JavaScript
function Test() {
console.log("started");
var xhttp = new XMLHttpRequest();
xhttp.responseType = "arraybuffer";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.response);
var bytes = new Uint8Array(this.response); // pass byte response to this constructor
var blob=new Blob([bytes], { type: "*/*"});// change resultByte to bytes
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.click();
}
};
xhttp.open("POST", "http://localhost:8080/testService", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Accept", "*/*");
xhttp.send("{ \"Id\": \"12345678\" }");
}
Now for the line
var blob=new Blob([bytes], { type: "*/*"});
How do I know what type of file it is.... it wont let me stream it to the browser if I just leave it like */*
it needs to be a specific type.
Upvotes: 0
Views: 119
Reputation: 5119
As you stated out in the comments you need to get the content type header, you 've set for the response. Here 's a simple response, which shows how to get the content type header.
xhr = new XMLHttpRequest();
xhr.addEventListener('load', requestHandler);
xhr.open('GET', your_service_url_here);
xhr.send();
function requestHandler()
{
console.log(this.getResponseHeader('content-type'));
}
More about the XMLHttpRequest.getResponseHeader()
method you can read here.
For streaming reasons you can use so called data URIs.
<a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>
The caniuse.com entry for data URIs states out, that the support for data URIs is widely spread. To force an automatically download stream you can execute a click event on a dynamically generated data URI link.
Upvotes: 1