How to view files before downloading?

Asked

Viewed 827 times

2

I want a PDF (generated on my server) sent to my client and opened in a new tab before it is downloaded. I have already managed to have it downloaded directly when it comes from the server to the client, but now I need it to be displayed instead of downloaded.

I created an Express server in version 4.15.0 and my client was made in Vuejs using the Quasar Framework. Follow some codes to help understand the question:

Server:

pdfMake = printer.createPdfKitDocument(docDefinition);
let stream = pdfMake.pipe(fs.createWriteStream('../pdfs/Tabela.pdf'));
pdfMake.end();

stream.on('finish', function() { //Método síncrono que só efetua o download do arquivo
                                 // depois que o PDF está criado
    if (fs.existsSync('C:/Projetos/Relatorios/pdfs/Tabela.pdf')) {
        let file = 'C:/Projetos/Relatorios/pdfs/Tabela.pdf';
        res.send(file); //Este método está certo?? Se não, qual devo usar??
    }
})

Client:

axios({
      method: 'post',
      url: '/server/gerarpdf',
      responseType: 'arraybuffer',
      data: this.pessoas
    })
    .then(function (response) {
      let blob = new Blob([response.data], {type: 'application/pdf'})
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      //Comentei o método abaixo pois ele efetuava o download, qual método devo utilizar para que o PDF seja visualizado ao invés de baixado??
      // link.download = 'TabelaTeste.pdf'
      link.click()
    })

1 answer

0


Open your link in a new tab:

let link = document.createElement('a')    
link.target = '_blank'
let url = window.URL.createObjectURL(blob);
link.href = url.replace(/([\w]{8})-([\w]{4}-){3}([\w]{12})/g, 'meuarquivo.pdf');
  • let options = {
 root: '../pdfs/',
 dotfiles: 'deny'
 };
 let fileName = 'Tabela.pdf';
 res.sendFile(fileName, options, function (err) {
 if (err){
 console.log(err)
 }else{
 console.log(fileName + ' foi enviado!')
 } And the server being so is correct??

  • Because it is opening the file, but the name is " 4098840a-9687-4fad-aa36-7e6f16f5a018"

  • I believe he will not obey the name sent by the server, try to uncomment the line of code link.download @Leonardoebert

  • After uncommenting the line link.download the file was only downloaded, without opening in new tab

  • Of a console.log(window.URL.createObjectURL(blob)) to see the URL format. We can rename to it @Leonardoebert

  • That’s what appeared on the console: blob:http://localhost:8080/960619d0-a0fa-4a6e-ba0e-6c0380669f1f

  • Edited by @Leonardoebert

  • I tested and it didn’t work, nothing happens when I click the button...

  • I checked the URL in the browser and it looks like this: "blob:http://localhost:8080/2050102b-7041-4cfa-9ebf-0c05af158005"

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.