handle Response with content-type: application/octet-stream [React]
Sometimes server will provide an interface with application/octet-stream, usually it's related with file operator, so how we handle this using js?
Actually it's very easy, make it as a download content will be okay.
e.g.
cache-control: no-cache, no-store, max-age=0, must-revalidate
connection: close
content-disposition: attachment; filename=111.txt
content-type: application/octet-stream
Date: Mon, 28 Jan 2019 08:31:00 GMT
expires: 0
pragma: no-cache
referrer-policy: no-referrer
transfer-encoding: chunked
x-content-type-options: nosniff
x-frame-options: DENY
X-Powered-By: Express
x-xss-protection: 1 ; mode=block
We can handle this response by following codes:
function handleResponse = response => {
response.blob().then(blob => {
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
console.log(url);
link.href = url;
link.download = '111.txt';
link.click();
})
}
Then you'll see browser will call download action.
Written by soolaugust
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#