@RequestMapping(value = "/downloadExeclTemp", method = RequestMethod.POST)
@ResponseBody
public void downloadExeclTemp(HttpServletRequest request, HttpServletResponse response,@RequestParam(value="id")String id,@RequestParam(value="name")String name) {
try {
String filePath = this.getRequest().getServletContext().getRealPath("\\") + "path.xlsx";
String outFileName = "pd-"+System.currentTimeMillis()+ ".xlsx";
InputStream is = null;
File outfile = null;
OutputStream os = null;
// 下载文件
try {
outfile = new File(filePath);
is = new BufferedInputStream(new FileInputStream(filePath));
// 设置输出的格式
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.reset(); // 重置结果集
String header = request.getHeader("User-Agent").toUpperCase();
// 针对IE或者以IE为内核的浏览器:
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
outFileName = URLEncoder.encode(outFileName, "utf-8");
outFileName = outFileName.replace("+", "%20"); // IE下载文件名空格变+号问题
} else {
// 非IE浏览器的处理
outFileName = new String(outFileName.getBytes(), "ISO8859-1");
}
response.addHeader("Content-Disposition",
"attachment;filename=" + new String(outFileName.replaceAll(" ", ""))); // 返回头文件名
response.addHeader("Content-Length", "" + outfile.length()); // 返回头
// 文件大小
response.setContentType("application/octet-stream"); // 设置数据种类
// 循环取出流中的数据
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) > 0) {
response.getOutputStream().write(buffer, 0, len);
}
// 获取返回体输出权
os = new BufferedOutputStream(response.getOutputStream());
os.write(buffer); // 输出文件
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.flush();
os.close();
}
if (is != null) {
is.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
} catch (Exception e) {
logger.error("下载 "+name+" 模板文件-出错",e);
e.printStackTrace();
}
}
java 后台接收 form 下载文件
最新推荐文章于 2023-02-13 16:39:06 发布