Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

vue.js - How do I use blob for downloading file on javascript

I've seen a few answers on StackOverflow, people asked about how to use it. But none of them helped. Here's my code:

async fileDownload(id) {
      this.isLoading = true;
      try {
        const res = await downloadApi.downloadById(id);
        console.log(res.headers);
        let blob = new Blob([res.data], {type: res.headers['content-type']});
        let link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'file';
        link.click();
        URL.revokeObjectURL(link.href);
      } catch (e) {
        console.error(e);
      }
      this.isLoading = false;
    },

the function, request, and response are working fine. But when I download the file, the file doesn't open. enter image description here

Request header:

enter image description here

the response data: ...

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try it:

  let configHeaders = {
    responseType: 'blob'
  }
  axios.get('localhost:9090/api', configHeaders).then(response => {
    let fileURL = window.URL.createObjectURL(new Blob([ ...response ]))
    let fileLink = document.createElement('a')
    fileLink.href = fileURL
    fileLink.setAttribute('download', `file-name-${month}.txt`)
    document.body.appendChild(fileLink)
    fileLink.click()
  })

Maybe you need spread response. See:

new Blob([ ...response ])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...