javaweb简单的实现⽂件下载及预览@ResponseBody
@RequestMapping(value="/downloadFile")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception{
//解决乱码问题
String path = Parameter("path");
String fileName = Parameter("fileName");
path = MyUtils.isRandomCode(path);
fileName = MyUtils.isRandomCode(fileName);
try {
String filePath = path+fileName;
//⾼速浏览器以附件形式下载
//不同浏览器的编码不同,对中⽂进⾏编码,下载时输出名称是⽂件名
response.setHeader("Content-Disposition","attachment;filename="+fileName);
//获取⽂件的mimetype,如,他的mimetype就是 txt ,下载时,就以 txt 格式下载
String mimeType = fileName.substring(fileName.lastIndexOf(".") + 1);    //获取⽂件后缀,⽐如是 txt ⽂件,就是以txt格式下载
//设置响应的 mimetype
response.setContentType(mimeType);
//获取response 输出流,⽤来输出⽂件
ServletOutputStream out = OutputStream();
//接下来进⾏读取,以输⼊流的形式读取
FileInputStream in = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int len = 0;
while ((ad(buffer))!=-1){
out.write(buffer,0,len);
}
in.close();
} catch (Exception e) {
System.out.println("下载错误!");
}
}
这⾥有⼀个⼯具类,就是前端传过来的参数有可能会乱码,所以要判断⼀下是否乱码,有乱码的话就处理⼀下
package dules.api.util;
import java.io.UnsupportedEncodingException;
/**
* ⾃定义⼯具类
* @Author zhouhe
* @Date 2019/11/15 11:54
*/
public class MyUtils {
/**
* 判断是否是乱码,乱码的话进⾏处理,不乱码直接返回
* @param code
* @return
*/
public static String isRandomCode(String code) throws UnsupportedEncodingException {
if (!XUtil.isEmpty(code)) {
//判断是乱码 (GBK包含全部中⽂字符;UTF-8则包含全世界所有国家需要⽤到的字符。)
web下载官方下载if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(code))) {
code = new Bytes("ISO-8859-1"), "utf-8"); //转码UTF8
}
}
return code;
}
}
前端可以使⽤ window.location.href=请求路径,⽐如:
注意:
不能使⽤ajax请求后台下载⽂件,否则会有问题:
ajax请求只是个“字符型”的请求,即请求的内容是以⽂本类型存放的。⽂件的下载是以⼆进制形式进⾏的,ajax没法解析后台返回的⽂件流,所以⽆法处理⼆进制流response输出来下载⽂件,可以在浏览器中的network⾥⾯查看访问的地址,到response⼀栏就看见后台返回的数据:
解决⽅法:
⽂件直接下载(不需要传递参数),可以使⽤ < a href="/media">点击下载Excel < /a>
前端需要传递参数(如excel),可以在绑定⽅法⾥⾯ window.location.href=url
⽂件预览:
public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
if (isOnLine) { // 在线打开⽅式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
/
/ ⽂件名应该编码成UTF-8
} else { // 纯下载⽅式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
}
OutputStream out = OutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}
要注意在路径前加了file:///,否则会报错 java.MalformedURLException: unknown protocol: e
还有⼀点就是中⽂下载或者带空格的话可能会有问题,会出现中⽂乱码或者变成___,⽽空格会被截断,处理⽅式如下:
response.setHeader("Content-Disposition","attachment;filename="+fileName);
换成
response.setHeader("Content-Disposition","attachment; filename=\"" + new Bytes("gb2312"),"ISO-8859-1") + "\"");