控制器:
package com.awaimai.web; import org.hibernate.validator.constraints.Range; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import java.io.*; import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @Controller @Validated public class kzq { @RequestMapping(value="/test10") public String test10(HttpServletRequest request, HttpServletResponse response) { File file = new File("C:\Users\del\IdeaProjects\helloweb\src\main\resources\uploadFiles\", "12345.pdf"); if (file.exists()) { //设置响应类型,这里是下载pdf文件 response.setContentType("application/pdf"); //设置Content-Disposition,设置attachment,浏览器会激活文件下载框;filename指定下载后默认保存的文件名 //不设置Content-Disposition的话,文件会在浏览器内打卡,比如txt、img文件 response.addHeader("Content-Disposition", "attachment; filename=12345.pdf"); byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; // if using Java 7, use try-with-resources 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 (IOException ex) { // do something, // probably forward to an Error page } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { } } if (fis != null) { try { fis.close(); } catch (IOException e) { } } } } return "index"; } }
下载:
postman访问: