转载请注明:https://blog.csdn.net/qfashly/article/details/79499082
public class ResponseDownloadUtils {
private static Logger log = LoggerFactory.getLogger(ResponseDownloadUtils.class);
/**
* @Title: download
* @Description:
* @param response
* @param path
* @throws Exception
* @date 2018-3-9 下午4:12:53
*/
public static void download(HttpServletResponse response, String path) throws Exception {
File f = new File(path);
download(response, f, f.getName());
}
/**
* @Title: download
* @Description:
* @param response
* @param path
* @param fileName
* @throws Exception
* @date 2018-3-9 下午4:13:01
*/
public static void download(HttpServletResponse response, String path, String fileName) throws Exception {
File f = new File(path);
download(response, f, fileName);
}
/**
* @Title: download
* @Description:
* @param response
* @param file
* @param fileName
* @throws Exception
* @date 2018-3-9 下午4:13:13
*/
public static void download(HttpServletResponse response, File file, String fileName) throws Exception {
File f = file;
if (!f.exists()) {
return;
}
download(response, new FileInputStream(f), fileName);
}
/**
* @Title: download
* @Description:
* @param response
* @param fis
* @param fileName
* @date 2018-3-9 下午4:13:23
*/
public static void download(HttpServletResponse response, FileInputStream fis, String fileName) {
BufferedInputStream br = null;
OutputStream out = null;
try {
if (fis == null) {
response.sendError(404, "File not found!");
return;
}
br = new BufferedInputStream(fis);
byte[] buf = new byte[1024];
int len = 0;
response.reset();
String fileName2 = new String(fileName.getBytes(), "ISO8859-1");
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName2);
out = response.getOutputStream();
while ((len = br.read(buf)) != -1)
out.write(buf, 0, len);
out.flush();
br.close();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (out != null)
out.close();
} catch (IOException e) {
log.error(ExceptionUtils.getStackTrace(e));
}
}
}
}