nm5zvw
Last Updated: February 02, 2019
·
31
· soolaugust

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.