SpringMVC实现文件下载的两种方式及多文件下载
2024-08-24 19:30:44
1.传统方法
@RequestMapping("/download")
public String download( String fileName ,String filePath, HttpServletRequest request, HttpServletResponse response){
response.setContentType("text/html;charset=utf-8");
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
String downLoadPath = filePath; //注意不同系统的分隔符
// String downLoadPath =filePath.replaceAll("/", "\\\\\\\\"); //replace replaceAll区别 *****
System.out.println(downLoadPath);
try {
long fileLength = new File(downLoadPath).length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
2.利用springmvc提供的ResponseEntity类型,使用它可以很方便地定义返回的HttpHeaders和HttpStatus。
@RequestMapping("/download")
public ResponseEntity<byte[]> export(String fileName,String filePath) throws IOException {
HttpHeaders headers = new HttpHeaders();
File file = new File(filePath);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
3、多文件下载[2]
主要先下载到本地,并添加到压缩文件中,再读取压缩文件到数组中,而后将数组返回前台返回前台
//批量文件压缩后下载
@RequestMapping("/downLoad2")
public ResponseEntity<byte[]> download2(HttpServletRequest request) throws IOException {
//需要压缩的文件
List<String> list = new ArrayList<String>();
list.add("test.txt");
list.add("test2.txt");
//压缩后的文件
String resourcesName = "test.zip";
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("D:/"+resourcesName));
InputStream input = null;
for (String str : list) {
String name = "D:/"+str;
input = new FileInputStream(new File(name));
zipOut.putNextEntry(new ZipEntry(str));
int temp = 0;
while((temp = input.read()) != -1){
zipOut.write(temp);
}
input.close();
}
zipOut.close();
File file = new File("D:/"+resourcesName);
HttpHeaders headers = new HttpHeaders();
String filename = new String(resourcesName.getBytes("utf-8"),"iso-8859-1");
headers.setContentDispositionFormData("attachment", filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
}
另外需要注意的一点
ajax请求无法响应下载功能因为response原因,一般请求浏览器是会处理服务器输出的response,例如生成png、文件下载等,然而ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的。文件的下载是以二进制形式进行的,虽然可以读取到返回的response,但只是读取而已,是无法执行的,说白点就是js无法调用到浏览器的下载处理机制和程序。
推荐使用这种方式 自己构建表单进行提交
var form = $("<form>");
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");
form.attr("action",rootPath + "T_academic_essay/DownloadZipFile.do");
var input1 = $("<input>");
input1.attr("type","hidden");
input1.attr("name","strZipPath");
input1.attr("value",strZipPath);
$("body").append(form);
form.append(input1);
form.submit();
form.remove();
原文出处:
[1] panpanpan_, SpringMVC实现文件下载的两种方式, https://blog.csdn.net/a447332241/article/details/78998239
[2] qq_33422712, SpringMvc 下载和批量下载, https://blog.csdn.net/qq_33422712/article/details/79142350
最新文章
- 如何修复Windows 10 Enterprise 在9月更新后图片全部由绘图板打开的情况
- jQuery 中bind(),live(),delegate(),on() 区别(转)
- SqlServer性能检测和优化工具使用详细
- Oracle EBS Java Applet报错:找不到类
- linux查看rpm包创建的所有目录和文件
- poj2031 Building a Space Station
- InnoDB 存储引擎—索引
- MyBatis(3.2.3) - hello world
- simhash--文本排重
- Java基础-Eclipse环境搭建(02)
- [转]bitcoin API reference (JSON-RPC)
- hdu 4578 Transformation 线段树多种操作裸题
- java中获取两个时间中的每一天
- Java8学习笔记目录
- node 把文件封装一层文件夹
- spring+shiro+springmvc+maven权限卡控示例
- JVM虚拟机宕机_java.lang.OutOfMemoryError: unable to create new native thread
- spring boot 集成 shiro
- Invalid Host header 的解决方案
- w3cscholl的在线代码编辑工具
热门文章
- Spring Boot 框架下使用MyBatis访问数据库之基于XML配置的方式
- 微信小程序生命周期详解
- jQuery源码二之extend的实现
- 解决pip安装时速度慢的问题
- flask建表遇到的错误: flask,sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1071, &#39;Specified key was too long; max key length is 767 bytes&#39;)
- Dockerfile(从无到有创建镜像)
- 纯数据结构Java实现(11/11)(散列)
- js--动画
- HTML实现调用百度在线翻译API
- js定时器关闭,js定时器停止,一次关闭所有正在运行的定时器,自定义函数clearIntervals()一次关闭所有正在运行的定时器