开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天,点击查看活动详情
文件上传下载
文件下载
@RequestMapping("/test/down")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("img");
realPath = realPath + File.separator+"1.jpg";
//创建输入流
InputStream is = new FileInputStream(realPath);
//创建字节数组
//is.available() is字节流对应的所有字节数
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String, String> headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition", "attachment;filename=Sentiment.jpg");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bytes, headers, statusCode);
//关闭输入流
is.close();
return responseEntity;
}
文件上传
需要用到commons-fileupload
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
上传页面 (enctype 属性:表示将数据回发到服务器时浏览器使用的编码类型)
<form th:action="@{/test/upload}" enctype="multipart/form-data" method="post">
图片:<input type="file" name="photo" ><br>
<input type="submit" value="上传">
</form>
文件上传
@RequestMapping("/test/upload")
public String testUpload(MultipartFile photo, HttpSession session) throws IOException {
//获取上传的文件的文件名
String fileName = photo.getOriginalFilename();
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取当前工程下photo目录的真实路径
String photoPath = servletContext.getRealPath("photo");
//创建photoPath所对应的File对象
File file = new File(photoPath);
//判断file所对应目录是否存在
if(!file.exists()){
file.mkdir();
}
String finalPath = photoPath + File.separator + fileName;
//上传文件
photo.transferTo(new File(finalPath));
return "success";
}
上传后发现空指针,因为形参MultipartFile photo获取不到,这是就需要在SpringMVC.xml设置文件上传解析器 (由于这种bean管理方式不是基于类型的,所以需要加上id)
<!--文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
这是上传文件后,就会上传到photo目录中
文件重命名问题
如果此时再上传一个1.jpg,那么新上传的图片的二进制数据就会替换到原来的图片数据,呈现出将图片替换了的现象
此时就可以通过命名规范的方式解决此问题,一般可以用uuid或时间戳命名解决:
//获取文件后缀
String hzName = fileName.substring(fileName.lastIndexOf("."));
//通过uuid生成文件名
String uuid = UUID.randomUUID().toString();
//通过uuid和后缀拼接一个新文件
fileName=uuid+hzName;