package com.jeesite.modules.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
public class FileDownUtils {
private static Logger logger = LoggerFactory.getLogger(FileDownUtils.class);
/**
* 文件下载方法
* @param response
* @param filePath
* @param encode
*/
public static void download(HttpServletResponse response, String filePath, String encode) {
response.setContentType("text/html;charset=" + encode);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String downLoadPath = filePath;
try {
File file = new File(downLoadPath);
long fileLength = file.length();
String fileName = file.getName();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(encode), "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) {
logger.error(e.getMessage());
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
/**
* 以流的方式下载
* @param response
* @param filePath
* @param encode
* @return response
*/
public static HttpServletResponse downloadStream(HttpServletResponse response, String filePath,String fileName, String encode) {
response.setContentType("text/html;charset=" + encode);
try {
File f = ResourceUtils.getFile("src/main/webapp"+filePath.substring(3,filePath.length()));
filePath = f.getAbsolutePath();
// path是指欲下载的文件的路径
File file = new File(filePath);
// 取得文件的后缀名
// String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件
InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(encode), "ISO8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
logger.error(ex.getMessage());
}
return response;
}
/**
* 下载本地文件
* @param response
* @param filePath
* @param encode
*/
public static void downloadLocal(HttpServletResponse response, String filePath,String encode) {
response.setContentType("text/html;charset=" + encode);
try {
//获取根路径
File f = ResourceUtils.getFile("src/main/webapp"+filePath.substring(3,filePath.length()));
filePath = f.getAbsolutePath();
System.out.println(filePath);
// 读到流中
InputStream inStream = new FileInputStream(filePath); // 文件的存放路径
// path是指欲下载的文件的路径
File file = new File(filePath);
// 取得文件名
String fileName = file.getName();
// 设置输出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes(encode), "ISO8859-1"));
//response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
// 循环取出流中的数据
byte[] b = new byte[100];
int len;
while ((len = inStream.read(b)) > 0) {
response.getOutputStream().write(b, 0, len);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}
}
2.Controller
/**
* 下载客户文档
* @param filePath 路径
* @param response
* @return
*/
@PostMapping("downFile")
@ResponseBody
public String downFile(String filePath,HttpServletResponse response) {
//根据filePath得到相应下载信息
CrmFiles crmFiles = new CrmFiles();
crmFiles.setFilePath(filePath);
List<CrmFiles> list = crmFilesService.findList(crmFiles);
if(list.size()>0) {
FileDownUtils.downloadStream(response, filePath,list.get(0).getUploadFiles(), "utf-8");
}else {
return renderResult(Global.FALSE, text("客户文档不存在"));
}
return renderResult(Global.TRUE, text("下载客户文档成功"));
}
3.html,前端要用form表单提交,不然浏览器不弹下载框
{header:'${text("操作")}', name:'actions',align:"center", width:120, sortable:false, title:false, formatter: function(val, obj, row, act){
var actions = [];
var filePath = row.filePath;
actions.push('<form action="${ctx}/customerManage/crmFiles/downFile?filePath='+filePath+'" method="post"><button type="submit" class="btn btn-primary btn-sm">${text(' 下载')}</button></form>');
return actions.join('');
}}
4.页面