简体   繁体   中英

Download a pdf with server node and vue.js

I have a problem. I must create a link for download a pdf with server but when click on link the file is not downloaded.

it is important not to expose the PDF link in the client but download the file from the server.

please help me!

in front, I dit it


    <div class="historyNavBtns">
      <a
        v-if="isLoggedIn"
        href="/tutorial"
        @click="goLinkTutorial"
      >
        <fa-icon
          class="btn bg-blue"
          icon="info-circle"
        />
      </a>

my method to call api

  methods: {
    async goLinkTutorial () {
      try {
        await api.getLinkTutorial()
      } catch (error) {
        this.$store.dispatch('setMessage', { type: 'error', message: error, timeout: 2000 })
      }
    },
  },

}

in api.js

export async function getLinkTutorial () {
  console.log('test')
  const response = await apiClient.get('/tutorial')
  return response.data
}

In route

router.get('/', getTutorial)

in controller

import { techLogger } from '../util/logger.js'

export const getTutorial = (req, res) => {
  try {
    res.type('application/pdf').download(new URL('../upload-folder/tutorial.pdf', import.meta.url).pathname, 'tutorial.pdf')
  } catch (error) {
    techLogger.info(error)
  }
}

Instead of getting the downloaded document via axios (or the apiClient) you should create a link to it and click it:

    <div class="historyNavBtns">
      <a
        v-if="isLoggedIn"
        href="/tutorial"
        download="tutorial.pdf"
      >
        <fa-icon
          class="btn bg-blue"
          icon="info-circle"
        />
      </a>

If you insist on doing this in a click handler/in javascript you could also do:

export async function getLinkTutorial () {
  console.log('test')
  //const response = await apiClient.get('/tutorial')
  //return response.data
  var link = document.createElement('a');
  link.href = '/tutorial';
  link.setAttribute('download', 'tutorial.pdf');
  document.body.appendChild(link);
  link.click();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM