直接上代码:
@RequestMapping("/patchDownLoad")
public void patchDownLoad(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String patchName = request.getParameter("patchName");
String patchPath = request.getParameter("patchPath");
File file = new File(patchPath);
response.setContentType("application/octet-stream");
//下载显示的中文名,解决中文名称乱码问题
String downloadFileName = new String(patchName.getBytes("UTF-8"),"ISO-8859-1");
//application/octet-stream:二进制流数据
response.addHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
byte[] buffer = new byte[2014];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (Exception e) {
}
}
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
}
}
}
}
本文详细介绍了如何使用Spring MVC中的@Controller注解实现文件下载功能。通过@RequestMapping注解指定URL路径,利用HttpServletRequest获取请求参数,如文件名和路径。设置HttpServletResponse响应头以允许浏览器下载文件,并正确处理中文文件名的编码问题。文章还展示了如何读取文件并将其作为字节流发送到客户端,包括使用FileInputStream和BufferedInputStream进行文件读取,以及使用OutputStream将文件写入HTTP响应。
454

被折叠的 条评论
为什么被折叠?



