Home > Software design >  How can I trigger download base on API response?
How can I trigger download base on API response?

Time:03-23

I called an API to get the QR Code, I got the response back and was able to display it on the DOM as whatever the type user selected, but now I need to download it

I tried

axios
    .post(window.URL, body, { responseType: 'arraybuffer' })
    .then((response) => {
        console.log('get-serial', response.data)

        const base64 = btoa(new Uint8Array(response.data).reduce((data, byte) => data   String.fromCharCode(byte), ''))

        //download
        var img = new Image()
        img.src = 'data:image/jpeg;base64, '   base64
        return img
    })
    .catch((err) => {
        console.log('Something went wrong: ', err)
    })

I don't see any image download when that run.

CodePudding user response:

This works perfectly;

axios
    .post(window.URL, body, { responseType: 'arraybuffer' })
    .then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download',  'filename.ext')
        document.body.appendChild(link)
        link.click()
    })
  • Related