Problem description

Usually, we need to download files in the project, such as downloading Excel forms, PDF files and Word documents. Such functions are usually done by the back end, that is, the back end returns a stream file or a URL address.

But, actually, the front end can be done. Very simple, use the A tag download function. But be careful where static files are stored.

Note that the front-end does static resource downloads suitable for fixed data, do not interact with the database data, such as Excel templates, such as notes. Docx documents and so on. Conversely, the back-end is more appropriate.

steps

Step 1: Create a static folder under the public folder to store static resources

Create a new static folder under the public folder of our VUE project, which stores the static resource files we need to download, as shown in the picture below. Here I have stored a template. XLSX file, which will be downloaded later. The static folder contains PDF files, Word files, etc. The static folder can also be created for fine storage, as long as the path of the A tag download is correct, it is not described here.

Note that should be in the public folder new folder to store static resources, not in the SRC folder new folder to store static resources, because the public folder of documents resource will not be NPM run build packaging compilation. If you pack it up, you’ll see that the template.xlsx file is stored in dist/static

Step 2: Simulate a tag to download the file

Suppose we click a button to download a static resource, as follows:

// html
<el-button type="primary" plain @click="frontDownload"</el-button>//js
frontDownload() {
  var a = document.createElement("a"); // Create a  tag
  a.href = "/ static/templates. XLSX"; // Add the address to the href value of the a tag.
  a.download = "Downloaded."; // Set the name of the downloaded file
  a.style.display = "none"; // hide the a tag
  document.body.appendChild(a); // Append the A tag to the document object
  a.click(); // the href of a tag will be read, and the browser will automatically download
  a.remove(); // Delete a tag when used up
}
Copy the code

If it is in the form of the file address returned by the back end, the value of a.ref is the address returned by the back end.

conclusion

The above code can achieve a tag access front-end static resources, and download the function. A good memory is better than a bad pen. Write it down