1.效果
2. 后台
2.1 实体类加两个属性
上传的时候 保存属性
2.2 页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>文件下载</title> <style> .expa{ width:120px; height:80px; border:1px solid #F00} .expb{ width:200px; height:120px; border:1px solid #00F} </style> </head> <body> <h3>文件下载</h3> <div> <img alt="" src="${requestScope.user.filepath}" width="400px" height="300px"> </div><a href="${pageContext.request.contextPath }/download.action?filename=${requestScope.user.realname}"> ${requestScope.user.image.originalFilename } </a> </body> </html>2.3 后台 代码
/**
* 6. 下载文件 * request * filename * model * * Exception */ @RequestMapping(value="/download.action") public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename, Model model)throws Exception { //下载文件路径 // String path = request.getServletContext().getRealPath("/images/"); String temp =request.getServletContext().getContextPath(); String path = "D:/workspace"+temp+"/src/main/webapp/img"; File file = new File(path + File.separator + filename); HttpHeaders headers = new HttpHeaders(); //下载显示的文件名,解决中文名称乱码问题 String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1"); //通知浏览器以attachment(下载方式)打开图片 headers.setContentDispositionFormData("attachment", downloadFielName); //application/octet-stream : 二进制流数据(最常见的文件下载)。 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);// MediaType 用spring框架的 return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), // FileUtils 选择 org.apache.commons.io.FileUtils headers, HttpStatus.CREATED); }