Home > Mobile >  File download functionality in vue js
File download functionality in vue js

Time:11-04

I am new to development and trying first time this functionality. I am trying to download the file which is coming from the server as this form `

%PDF-1.2
%����
3 0 obj
<< 
/Linearized 1 
/O 5 
/H [ 760 157 ] 
/L 3908 
/E 3658 
/N 1 
/T 3731 
>> 
endobj
                                                                xref
3 15 
0000000016 00000 n
0000000644 00000 n
0000000917 00000 n
0000001068 00000 n
0000001224 00000 n
0000001410 00000 n
0000001589 00000 n
0000001768 00000 n
0000002197 00000 n
0000002383 00000 n
0000002769 00000 n
0000003172 00000 n
0000003351 00000 n
0000000760 00000 n
0000000897 00000 n
trailer
<<
/Size 18
/Info 1 0 R 
/Root 4 0 R 
/Prev 3722 
/ID[<d70f46c5ba4fe8bd49a9dd0599b0b151><d70f46c5ba4fe8bd49a9dd0599b0b151>]
>>
startxref
0
%EOF
      
4 0 obj
<< 
/Type /Catalog 
/Pages 2 0 R 
/OpenAction [ 5 0 R /XYZ null null null ] 
/PageMode /UseNone 
>> 
endobj
16 0 obj
<< /S 36 /Filter /FlateDecode /Length 17 0 R >> 
stream
H�b``�e``��

` Now in the UI I have did like this


downloadFile () {
  api.get(`ips/downloadAttachedFile/`   this.claimId, { responseType: 'Blob' }).then( res => {
    const downloadUrl = window.URL.createObjectURL(new Blob([res]),{ type: "application/pdf" });
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.setAttribute('download', 'test.pdf');
    document.body.appendChild(link);
    link.click();
    link.remove();
    URL.revokeObjectURL(link.href)
  })
}

when I am trying to download it, pdf is coming as blank file.

I want the data inside that pdf file to be displayed and if I have more type of files like .jpg, .doc etc so how can I download them with their extension. Can anyone help me with this

CodePudding user response:

You can try with FileSaver - works like a charm:

import saveAs from '@/lib/FileSaver.js';
import Axios from 'axios';

Axios.get(`ips/downloadAttachedFile/`   this.claimId, {
  responseType: 'blob',
}).then(response =>
{
  saveAs(new Blob([response.data], { type: 'application/octet-stream' }), response.filename, { autoBOM: false });
});

CodePudding user response:

You could try a timeout after clicking the button. Works for me.

const download = (data, name, type) => {
  const url = window.URL.createObjectURL(new Blob([data], { type }));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', name);
  document.body.appendChild(link);
  link.click();
  setTimeout(() => {
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }, 200);
};

applied to your case this would be

downloadFile () {
  api.get(`ips/downloadAttachedFile/${this.claimId}`, { 
    responseType: 'Blob' 
  }).then(res => {
    download(res, 'test.pdf', 'application/pdf')
  })
}
  • Related