导入依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
mvc配置文件中配置文件上传的信息
<!--3. 配置文件上传-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--3.1 总共上传的文件大小-->
<property name="maxUploadSize" value="10485760"/>
<!--3.2 每一个上传文件 的最大大小-->
<property name="maxUploadSizePerFile" value="2097152"/>
</bean>
前端代码
<form class="form-signin" method="post" action="/file/upload" enctype="multipart/form-data">
<input type="file" name="file" class="form-control" placeholder="请选择要上传的文件">
<button class="btn btn-lg btn-primary btn-block" type="submit">上传</button>
</form>
点击上传后 后端处理
@RequestMapping("file/upload")
public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
ServletContext sc = request.getServletContext();
//1. 得到上传的文件名
String filename = file.getOriginalFilename();
System.out.println("上传的文件名: "+filename);
//2. 得到后缀名
String suffix = filename.substring(filename.indexOf("."));
//3. 随机生成一个uuid作为文件名
String name = UUID.randomUUID().toString();
//4. 得到upload文件夹的真实的物理路径
String realPath = sc.getRealPath("/upload");
System.out.println("真实的物理路径: "+realPath);
//5. 得到最终要上传的文件 对象
File dest = new File(realPath,name+suffix);
System.out.println("上传的文件:"+dest);
//6. 进行文件上传
file.transferTo(dest);
//7. 跳转到文件列表页面
return "fileList";
}
文件下载
前端构建下载链接地址
<%
String realPath = application.getRealPath("/upload");
File dirs = new File(realPath);
File[] files = dirs.listFiles();
for (File file : files) {
out.println("<li><a href='/file/download?fileName="+file.getName()+"'>" + file.getName() + "</a></li>");
}
%>
http://localhost:8005/file/download?fileName=31b7b240-c437-4191-a1a6-e78b60aa3cd4.jpg
后端处理
@RequestMapping("file/download")
public ResponseEntity<byte[]> download(String fileName, HttpServletRequest request){
//1. 得到ServletContext
ServletContext sc = request.getServletContext();
//2. 得到文件的完整路径
String realPath = sc.getRealPath("/upload");
System.out.println("真实的物理路径: "+realPath);
//3. 得到真实的文件对象
File dest = new File(realPath,fileName);
System.out.println("文件对象:"+dest);
//4. 将文件对象读取到字节数组中
byte[] bytes = FileUtil.readBytes(dest);
//5. 设置请求头,并以附件的形式打开,出现“另存为”对话框
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment",fileName); //出现“另存为”
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //以二进制流的形式打开
//6. 返回
return new ResponseEntity<>(bytes,headers, HttpStatus.CREATED);
}