1

I have the following code

<a href="../../assets/all-work/proto/pdf-test.pdf" download>Download</a>

It's inside a vue component which is located in src/components/Home/Proto.vue and the file is located in src/assets/all-work/proto/pdf-test.pdf, when I click download it downloads something completely illegible, why's that and how could I fix it?

3
  • The urls will be relative to the nodes baseURI, which will probably be the one of your Document, usually itself set to the current location, but not of where your code-source is fetched from.
    – Kaiido
    Commented Jan 31, 2020 at 2:17
  • what would be the correct way to write it? I'm very confused, I use the same path for images and it works perfectly
    – pinkWojak
    Commented Jan 31, 2020 at 2:51
  • Hmmm yeah I also get 'Failed - No file' when I try this Commented Jan 31, 2020 at 3:03

1 Answer 1

1

I'm going to assume you're using Vue CLI.

The default configuration generated by the Vue CLI has special handling for images. To get the same thing working for PDFs you need to configure it yourself.

Firstly, you'll need to explicitly use require on your href:

<a :href="require('../../assets/all-work/proto/pdf-test.pdf')" download>Download</a>

In some scenarios, such as the src attribute of an <img>, the wrapping with require is performed automatically. For an <a href> it isn't.

You'll then run into a Webpack loader error because Webpack has no idea what to do with a .pdf file.

To fix that you'll need to configure a file-loader in vue.config.js:

module.exports = {
  chainWebpack (config) {
    config.module.rule('pdf')
      .test(/\.pdf$/)
      .use('file-loader')
      .loader('file-loader')
  }
}

If you don't already have a vue.config.js file then you'll need to create one. It goes at the top level, next to your package.json.

If you do already have a vue.config.js then you'll need to merge the chainWebpack property in, alongside your existing configuration.

By default the file will be renamed to a hash based on its content. It you want to retain the original file name you can configure that instead:

chainWebpack (config) {
  config.module.rule('pdf')
    .test(/\.pdf$/)
    .use('file-loader')
    .loader('file-loader')
    .options({
      name: '[name].[ext]'
    })
}

More details on the name option can be found at:

https://webpack.js.org/loaders/file-loader/#name

Not the answer you're looking for? Browse other questions tagged or ask your own question.