PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 6, 2022

[FIXED] How can I trigger download base on API response?

 May 06, 2022     image, vue-component, vue.js, vuejs2, vuetify.js     No comments   

Issue

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.


Solution

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()
    })


Answered By - code-8
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing