一、上传文件
1.jsp页面上传form表单需配置
enctype="multipart/form-data"
2.Jsp页面定义文件域
<input type="file" name="file"/>
3.后台代码上传方法参数传递
@RequestParam(value="file", required=false) MultipartFile file
4.指定上传文件的路径
String savePath = request.getServletContext().getRealPath("upload");
5.获取文件后缀名
int suffixIndex = file.getOriginalFilename().indexOf(".");
String suffixName = file.getOriginalFilename().substring(suffixIndex);
6.生成新的文件名称
7.检测文件
File targetFile = new File(savePath, newFileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
8.上传文件
file.transferTo(targetFile);
9.配置spring-mvc.xml上传文件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>32505856</value>
</property>
<property name="uploadTempDir">
<value>/upload/</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
二、下载文件
1.jsp页面定义下载链接地址
<a href="userController/downloadPhoto.do?fileName=${u.headPhoto }"></a>
2.后台方法返回值定义ResponseEntity<byte[]>
public ResponseEntity<byte[]> downloadPhoto(){}
3.方法参数定义文件名称
@RequestParam("fileName")String fileName)
4.获取源文件路径
String sourcePath = request.getServletContext().getRealPath(fileName);
5.获取源文件
File sourceFile = new File(sourcePath);
6.定义头部文件信息以及文件名称
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", fileName.substring(7));
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
7.文件下载
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>
(FileUtils.readFileToByteArray(sourceFile), headers, HttpStatus.CREATED);