springmvc学习篇——文件下载
1.前端jsp页面写个超链接跳进去
<a href="${pageContext.request.contextPath}/springmvc/fileDowload">点击下载</a>
2.文件下载的返回类型要用 ResponseEntity
@Controller //该注解表将当前类交给spring容器管理
@Scope("prototype")
@RequestMapping("/springmvc") //该注解起到限定范围的作用
public class MyController{
@RequestMapping("/fileDowload")
public ResponseEntity<byte[]> dowload() throws IOException{
//指定下载文件
File file = new File("D:/demo/QQ浏览器截图20190611144849.png");
InputStream is = new FileInputStream(file);
//创建字节数组,并且设置数组大小为预估的文件字节数
byte[] body = new byte[is.available()];
//将输入流中字符存储到缓存数组中
is.read(body);
//获取下载显示的文件名,并解决中文乱码
String name = file.getName();
String downLoadFileName = new String(name.getBytes("UTF-8"),"ISO-8859-1");
//设置Http响应头信息,并且通知浏览器以附件的形式进行下载
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Disposition", "attachment;filename="+downLoadFileName);
//设置Http响应状态信息
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body, httpHeaders, status);
return responseEntity;
}
}