springboot+vue实现页面下载文件
程序员文章站
2022-05-15 15:22:06
本文实例为大家分享了springboot+vue页面下载文件的具体代码,供大家参考,具体内容如下1.前端代码: &...
本文实例为大家分享了springboot+vue页面下载文件的具体代码,供大家参考,具体内容如下
1.前端代码:
<template v-slot:operate="{ row }"> <vxe-button style="color: #409eff; font-weight: bolder" class="el-icon-download" title="成果下载" circle @click="downloadfile(row)"></vxe-button> </template> downloadfile(row) { window.location = "http://localhost:8001/file/downloadfile?taskid=" + row.id; }
2.后端代码:
package com.gridknow.analyse.controller; import com.alibaba.fastjson.json; import com.gridknow.analyse.entity.datainfo; import com.gridknow.analyse.service.fileservice; import com.gridknow.analyse.utils.download; import com.gridknow.analyse.utils.result; import org.springframework.beans.factory.annotation.autowired; import org.springframework.beans.factory.annotation.value; import org.springframework.core.io.inputstreamresource; import org.springframework.http.httpheaders; import org.springframework.http.mediatype; import org.springframework.http.responseentity; import org.springframework.stereotype.controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.multipartfile; import org.springframework.web.multipart.multiparthttpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.*; import java.util.list; import java.util.map; /** * @classname filecontroller * @description: todo * @author administrator * @date 2020/8/20 14:02 * @version todo **/ @controller @requestmapping("/file") public class filecontroller { @value("${gridknow.mltc.imgurl}") private string imgurl; @autowired private fileservice fileservice; @crossorigin @requestmapping(value = "/upload", method = requestmethod.post) @responsebody public result upload(multiparthttpservletrequest request) { list<multipartfile> multipartfiles = request.getfiles("file"); map<string, object> map = (map<string, object>) json.parse(request.getparameter("body")); string companyid = request.getparameter("companyid"); string companyname = request.getparameter("companyname"); boolean bool = fileservice.uploadandinsert(multipartfiles, map, companyid, companyname); if (bool) { return new result(200); } else { return new result(500); } } @getmapping("/downloadfile") public responseentity<object> downloadfile(@requestparam("taskid") string taskid, httpservletresponse response) { datainfo datainfo = fileservice.querytaskbyid(taskid); if (datainfo == null) { return null; } file file = new file(datainfo.getresponseurl()); // 文件下载 if (file.isfile()) { return downloadfile(taskid); } // 文件夹压缩成zip下载 if (file.isdirectory()) { string parent = file.getparent(); // 创建临时存放文件夹 file temdir = new file(parent + "/" + taskid); if (!temdir.exists()) { temdir.mkdirs(); } // 将需要下载的文件夹和内容拷贝到临时文件夹中 try { download.copydir(datainfo.getresponseurl(), parent + "/" + taskid); } catch (ioexception e) { e.printstacktrace(); } // 设置头部格式 response.setcontenttype("application/zip"); response.setheader("content-disposition", "attachment; filename="+taskid+".zip"); // 调用工具类,下载zip压缩包 try { download.tozip(temdir.getpath(), response.getoutputstream(), true); } catch (ioexception e) { e.printstacktrace(); } // 删除临时文件夹和内容 download.delallfile(new file(parent + "/" + taskid)); } return null; } public responseentity<object> downloadfile(string taskid) { datainfo datainfo = fileservice.querytaskbyid(taskid); if (datainfo == null) { return null; } file file = new file(datainfo.getresponseurl()); string filename = file.getname(); inputstreamresource resource = null; try { resource = new inputstreamresource(new fileinputstream(file)); } catch (exception e) { e.printstacktrace(); } httpheaders headers = new httpheaders(); headers.add("content-disposition", string.format("attachment;filename=\"%s", filename)); headers.add("cache-control", "no-cache,no-store,must-revalidate"); headers.add("pragma", "no-cache"); headers.add("expires", "0"); responseentity<object> responseentity = responseentity.ok() .headers(headers) .contentlength(file.length()) .contenttype(mediatype.parsemediatype("application/octet-stream")) .body(resource); return responseentity; } }
工具类
package com.gridknow.analyse.utils; import lombok.extern.slf4j.slf4j; import java.io.*; import java.util.zip.zipentry; import java.util.zip.zipoutputstream; /** * @classname download * @description: todo * @author administrator * @date 2020/9/2 9:54 * @version todo **/ @slf4j public class download { private static final int buffer_size = 2 * 1024; public static void tozip(string srcdir, outputstream out, boolean keepdirstructure) throws runtimeexception { long start = system.currenttimemillis(); zipoutputstream zos = null; try { zos = new zipoutputstream(out); file sourcefile = new file(srcdir); compress(sourcefile, zos, sourcefile.getname(), keepdirstructure); long end = system.currenttimemillis(); log.info("压缩完成,耗时:" + (end - start) + " ms"); } catch (exception e) { throw new runtimeexception("zip error from ziputils", e); } finally { if (zos != null) { try { zos.close(); } catch (ioexception e) { e.printstacktrace(); } } } } /** * 递归压缩方法 * * @param sourcefile 源文件 * @param zos zip输出流 * @param name 压缩后的名称 * @param keepdirstructure 是否保留原来的目录结构, true:保留目录结构; * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败) * @throws exception * */ private static void compress(file sourcefile, zipoutputstream zos, string name, boolean keepdirstructure) throws exception { byte[] buf = new byte[buffer_size]; if (sourcefile.isfile()) { // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字 zos.putnextentry(new zipentry(name)); // copy文件到zip输出流中 int len; fileinputstream in = new fileinputstream(sourcefile); while ((len = in.read(buf)) != -1) { zos.write(buf, 0, len); } // complete the entry zos.closeentry(); in.close(); } else { file[] listfiles = sourcefile.listfiles(); if (listfiles == null || listfiles.length == 0) { // 需要保留原来的文件结构时,需要对空文件夹进行处理 if (keepdirstructure) { // 空文件夹的处理 zos.putnextentry(new zipentry(name + "/")); // 没有文件,不需要文件的copy zos.closeentry(); } } else { for (file file : listfiles) { // 判断是否需要保留原来的文件结构 if (keepdirstructure) { // 注意:file.getname()前面需要带上父文件夹的名字加一斜杠, // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了 compress(file, zos, name + "/" + file.getname(), keepdirstructure); } else { compress(file, zos, file.getname(), keepdirstructure); } } } } } /** * 拷贝文件夹 * * @param oldpath 原文件夹 * @param newpath 指定文件夹 */ public static void copydir(string oldpath, string newpath) throws ioexception { file file = new file(oldpath); //文件名称列表 string[] filepath = file.list(); if (!(new file(newpath)).exists()) { (new file(newpath)).mkdir(); } for (int i = 0; i < filepath.length; i++) { if ((new file(oldpath + file.separator + filepath[i])).isdirectory()) { copydir(oldpath + file.separator + filepath[i], newpath + file.separator + filepath[i]); } if (new file(oldpath + file.separator + filepath[i]).isfile()) { copyfile(oldpath + file.separator + filepath[i], newpath + file.separator + filepath[i]); } } } /** * 拷贝文件 * * @param oldpath 资源文件 * @param newpath 指定文件 */ public static void copyfile(string oldpath, string newpath) throws ioexception { file oldfile = new file(oldpath); file file = new file(newpath); fileinputstream in = new fileinputstream(oldfile); fileoutputstream out = new fileoutputstream(file);; byte[] buffer=new byte[2097152]; while((in.read(buffer)) != -1){ out.write(buffer); } in.close(); out.close(); } /** * 删除文件或文件夹 * @param directory */ public static void delallfile(file directory){ if (!directory.isdirectory()){ directory.delete(); } else{ file [] files = directory.listfiles(); // 空文件夹 if (files.length == 0){ directory.delete(); system.out.println("删除" + directory.getabsolutepath()); return; } // 删除子文件夹和子文件 for (file file : files){ if (file.isdirectory()){ delallfile(file); } else { file.delete(); system.out.println("删除" + file.getabsolutepath()); } } // 删除文件夹本身 directory.delete(); system.out.println("删除" + directory.getabsolutepath()); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。