vue to Download File Stream Complete Front and Back End Code

  • 2021-09-20 19:31:52
  • OfStack

How does our front end handle the file stream returned by our back end when using Vue

First of all, the backend returns to the flow. Here I take out the action of the flow. I need to use it in many places


/**
 *  Download a single file 
 *
 * @param docId
 */
 @GetMapping("/download/{docId}")
 public void download(@PathVariable("docId") String docId,
       HttpServletResponse response) {
  outWrite(response, docId);
 }
 
 /**
 *  Output file stream 
 * @param response
 * @param docId
 */
 private void outWrite(HttpServletResponse response, String docId) {
  ServletOutputStream out = null;
  try {
   out = response.getOutputStream();
   //  Disable image caching. 
   response.setHeader("Pragma", "no-cache");
   response.setHeader("Cache-Control", "no-cache");
   response.setDateHeader("Expires", 0);
   byte[] bytes = docService.downloadFileSingle(docId);
   if (bytes != null) {
    MagicMatch match = Magic.getMagicMatch(bytes);
    String mimeType = match.getMimeType();
    response.setContentType(mimeType);
    out.write(bytes);
   }
   out.flush();
  } catch (Exception e) {
   UnitedLogger.error(e);
  } finally {
   IOUtils.closeQuietly(out);
  }
 }

Front end Here I introduced a component js-file-download


npm install js-file-download --save

Then add it in the Vue file


import fileDownload from "js-file-download";

 //  Document Action Column Corresponding Events 
 async handleCommand(item, data) {
  switch (item.key) {
  case "download":
   var res = await this.download(data);
   return fileDownload(res, data.name);
  ...
  default:
  }
  //  Refresh the list of the current level 
  const folder = this.getLastFolderPath();
  this.listClick(folder.folderId, folder.name);
 },
 //  Download 
 async download(row) {
  if (this.isFolder(row.type)) {
  return FolderAPI.download(row.id);
  } else {
  return DocAPI.download(row.id);
  }
 },

docAPI js Note that responseType needs to be set


/**
 *  Download a single file 
 * @param {*} id
 */
const download = (id) => {
 return request({
 url: _DataAPI.download + id,
 method: "GET",
 responseType: 'blob'
 });
};

You can download it successfully.

For the learning tutorial of vue. js, please click on the special vue. js component learning tutorial and Vue. js front-end component learning tutorial to learn.


Related articles: