上一章我们讲过如何将文件上传,这一章我们将实现将上传的文件下载下来。
1、index.jsp和success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>上传文件</h2>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="photo"/>
<input type="submit" name="上传">
</form>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: Mr Wei
Date: 2020/6/5
Time: 15:53
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<html>
<head>
<title>上传成功页面</title>
</head>
<body>
<a href="/download?filename=${fname}">下载</a>
<img src="/uploadFile/${fname}" width="200px" height="150px">
</body>
</html>
2、Controller实现类
@RequestMapping("/download")
public ResponseEntity<byte[]> test(String filename, HttpServletRequest request) throws IOException{
String serverpath= request.getRealPath("/uploadFile");
//真实路径
serverpath=serverpath+"/"+filename;
//创建http头信息的对象
HttpHeaders header=new HttpHeaders();
//标记以流的方式做出响应
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//设置以弹窗的方式提示用户下载
//attachment 表示以附件的形式响应给客户端
// header.setContentDispositionFormData("attachment", URLEncoder.encode(filename,"utf-8"));
File f=new File(serverpath);
ResponseEntity<byte[]> resp=
new ResponseEntity<byte[]>
(FileUtils.readFileToByteArray(f), header, HttpStatus.CREATED);
return resp;
}
网友评论