关于文件的下载,示例代码如下。

/**
* @author: BNTang
*/
@Controller
public class MyFirstController {
@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpSession httpSession) throws Exception {
// 1.获取 ServletContext
ServletContext servletContext = httpSession.getServletContext();

// 2.获取路径
String realPath = servletContext.getRealPath("/images/zdy.jpg");

// 3.创建一个输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
byte[] bytes = new byte[fileInputStream.available()];

// 4.将文件流读取到数组当中
fileInputStream.read(bytes);

// 5.创建请求头
HttpHeaders httpHeaders = new HttpHeaders();

// 6.对文件名进行编码
String fileEncode = URLEncoder.encode("周冬雨.jpg", "UTF-8");

// 7.告诉浏览器以附件的形式下载文件
httpHeaders.add("Content-Disposition", "attachment;filename=" + fileEncode);

// 8.设置响应码
HttpStatus httpStatus = HttpStatus.OK;

ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, httpStatus);

// 9.关闭流
fileInputStream.close();

return responseEntity;
}
}

编写好了之后启动工程,发送请求效果如下所示。

SpringMVC-关于文件的下载_文件名