How to make the response as downloading as an attachment on browser, after getting back binary?

Viewed 70

I am sending a API request to a endpoint, which is supposed to give me back a powerpoint file.

However, in my response it is a bunch of binary code.

The header is content-type: 'application/octet-stream'

For example,

 "PK\u0003\u0004\u0014\u0000\u0000\u0000\b\u0000�\u0015'U��O�.\u000

Here is my axios in my code for calling the api,

export const getPtt = pptRequests => {
  const response = new Promise((resolve, reject) => {
    axios
      .post(
        `url`,
        pptRequests 
      )
      .then(data => {

        resolve(data)
      })
      .catch(err => {
        reject(err)
      })
  })
return response 

}

May I know how to decode the binary code, so I can make it will be downloading like below after sending it out

Edit:

here is where I call the function

 const handleGeneratePtt = () => {
    
    const pptRequests  = getPttRequests()
    getPtt (pptRequests ) // how to make it start downloading a ppt?
   
  }

enter image description here

Edit:

    export const getPtt = pptRequests => {
      const response = new Promise((resolve, reject) => {
        axios
          .post(
            `url`,
            pptRequests 
          )
          .then(data => {
const blob = new Blob([new Uint8Array(response.data)])
            const url = window.URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.setAttribute('style', 'display:none;')
            document.body.appendChild(a)
            a.href = url
            a.download = 'filename'
            a.click()
            a.remove()
            resolve(data)
          })
          .catch(err => {
            reject(err)
          })
      })
    return response 

    }
1 Answers

convert your data into blob (wether it's base64, octate, arraybuffer etc)

const blob = new Blob([data])

create objectURL for that

const url = window.URL.createObjectURL(blob)

create hidden dom element (so it works in all browsers)

const a = document.createElement('a');
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);

attach file to hidden element and click hidden element to download. remove after

a.href = url;
a.download = filename;
a.click();
a.remove();

just make sure to make your data into blob

Related