java通用文件下载
前端:简单的一个标签
<a href="../emp/OriDownload.do?fileName=421785d6-d76c-46a5-86b4-2cfcb9d0e0fbbanner1.png">图片</a>
后端代码:
/**
* javaweb通用文件下载
*
* @throws IOException
*
*/
@RequestMapping("/OriDownload")
public Result OriDownload(String fileName, HttpServletRequest Request, HttpServletResponse Response)
throws IOException {
// 获取文件名
System.out.println(fileName);
String path = Request.getSession().getServletContext().getRealPath("/img");
// 拼接文件路径
String pathAndFilename = path + "\\" + fileName;
System.out.println(pathAndFilename);
// 设置响应头和客户端保存文件名
Response.setCharacterEncoding("utf-8");
Response.setContentType("multipart/form-data");
Response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
// 创建文件对象
File file = new File(pathAndFilename);
// 创建字节数组
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(file);
output = Response.getOutputStream();
// 循环写入输出流
byte[] b = new byte[2048];
int length;
while ((length = input.read(b)) > 0) {
output.write(b, 0, length);
}
return new Result(true, "操作完成");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new Result(false, "操作失败");
} finally {
input.close();
output.close();
}
}
思路简单:以二进制流的方式读出写入。