javascript - Vue : how to download a file to browser using the download tag - Stack Overflow

I'm using axios and want to download a PDF and an image file.I can download both and open the imag

I'm using axios and want to download a PDF and an image file.

I can download both and open the image, but, when I try to open the PDF file, it doesn't open.

downloadItem({ url, name }) {
      axios
        .get(url, { responseType: 'blob' })
        .then((response) => {
          const blob = new Blob([response.data], { type: response.data.type });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = name;
          link.click();
          URL.revokeObjectURL(link.href);
        })
        .catch(console.error);
    },

Can anybody help me ? Sorry for my English.

I'm using axios and want to download a PDF and an image file.

I can download both and open the image, but, when I try to open the PDF file, it doesn't open.

downloadItem({ url, name }) {
      axios
        .get(url, { responseType: 'blob' })
        .then((response) => {
          const blob = new Blob([response.data], { type: response.data.type });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = name;
          link.click();
          URL.revokeObjectURL(link.href);
        })
        .catch(console.error);
    },

Can anybody help me ? Sorry for my English.

Share Improve this question edited May 31, 2020 at 1:20 Littm 4,9474 gold badges33 silver badges39 bronze badges asked May 30, 2020 at 22:08 Daniel AlmeidaDaniel Almeida 512 silver badges7 bronze badges 2
  • Is there any error in the console? – ssc-hrep3 Commented May 30, 2020 at 22:33
  • itsolutionstuff./post/… – sailfish009 Commented May 31, 2020 at 11:12
Add a ment  | 

1 Answer 1

Reset to default 3

Would this work for you?

axios
.get(url, {
  headers: {
    'Accept': 'application/pdf'
  },
  responseType: 'blob' })
.then(function (response) {
  switch ([WHAT IS YOUR TYPE]) {
    case "image": {
      const blob = new Blob([response.data], { type: response.data.type });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = name;
      link.click();
      URL.revokeObjectURL(link.href);
      break
    }
    case "pdf": {
      const blob = new Blob([response.data], { type: 'application/pdf' })
      const objectUrl = window.URL.createObjectURL(blob)
      window.open(objectUrl)
      elt.impressionEnCours = false
      break
    }
  }
})
.catch(function (error) {
  console.log(JSON.stringify(error))
})

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745221574a4617273.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信