<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>学生信息上传成功</h1> <table> <tr> <td>学号:</td> <td th:text="${student.getStuId()}"></td> </tr> <tr> <td>姓名:</td> <td th:text="${student.getStuName()}"></td> </tr> <tr> <td>年龄:</td> <td th:text="${student.getAge()}"></td> </tr> <tr> <td>照片:</td> <td th:each="p:${student.getPath()}"> <img th:src="${#servletContext.getContextPath()}+'/upload/'+${p}" width='200px' height='200px'/><br> <!--图片下载的超链接--> <a th:href="@{/downLoadFile(fileName=${p})}">点击下载图片</a> </td> </tr> </table> </body> </html>
package net.biancheng.c.controller; import org.apache.commons.io.FileUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; @Controller public class DownLoadController { /** * 文件下载 * * @param request * @param fileName * @return * @throws IOException */ @RequestMapping("/downLoadFile") public ResponseEntity<byte[]> downLoadFile(HttpServletRequest request, String fileName) throws IOException { //得到图片的实际路径 String realPath = request.getServletContext().getRealPath("/upload/" + fileName); //创建该图片的对象 File file = new File(realPath); //将图片数据读取到字节数组中 byte[] bytes = FileUtils.readFileToByteArray(file); //创建 HttpHeaders 对象设置响应头信息 HttpHeaders httpHeaders = new HttpHeaders(); //设置图片下载的方式和文件名称 httpHeaders.setContentDispositionFormData("attachment", toUTF8String(fileName)); httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK); } /** * 下载保存时中文文件名的字符编码转换方法 */ public String toUTF8String(String str) { StringBuffer sb = new StringBuffer(); int len = str.length(); for (int i = 0; i < len; i++) { // 取出字符中的每个字符 char c = str.charAt(i); // Unicode码值为0~255时,不做处理 if (c >= 0 && c <= 255) { sb.append(c); } else { // 转换 UTF-8 编码 byte b[]; try { b = Character.toString(c).getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); b = null; } // 转换为%HH的字符串形式 for (int j = 0; j < b.length; j++) { int k = b[j]; if (k < 0) { k &= 255; } sb.append("%" + Integer.toHexString(k).toUpperCase()); } } } return sb.toString(); } }
图1:图片上传成功
图2:点击链接下载图片
本文链接:http://task.lmcjl.com/news/12735.html