1、文件上传
<formth:action="@{/testUP}"method="post"enctype="multipart/form-data">
头像:<inputtype="file"name="photo">
<inputtype="submit"value="上传">
</form>
图片想要在页面显示可以如下操作:
localhost:8080/项目名/images/图片名
<imgth:src="@{/image/13.jpg}">
处理文件上传的依赖
<!--处理文件上传的依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.5</version>
</dependency>
上传代码:
@RequestMapping("/testUP")
publicStringtestUP(MultipartFilephoto, HttpSessionsession) throwsIOException {
//获取上传的文件的文件名
Stringfilename=photo.getOriginalFilename();
//==========解决文件重名=========
//获取上传的文件的后缀名
StringsubstringName=filename.substring(filename.lastIndexOf("."));
//将UUID作为文件名
Stringuuid=UUID.randomUUID().toString();
//将uuid和后缀名拼接后的结果作为最终的文件名
filename=uuid+substringName;
//====================
//通过ServletContext获取服务器中photo目录的路劲
ServletContextcontext=session.getServletContext();
//获取服务器中文件的真实路劲
Stringimage=context.getRealPath("image");
Filefile=newFile(image);
//判断文件是否存在
if (!file.exists()){
file.mkdir();
}
StringfinalPath=image+File.separator+filename;
//将图片写入本地
//会写入到target文件下
photo.transferTo(newFile(finalPath));
return"success";
}
2、文件下载
使用ResponseEntity实现下载文件功能
@RequestMapping("/testDown")
publicResponseEntity<byte[]>testDown(HttpSessionsession) throwsIOException {
//获取ServletContext对象
ServletContextservletContext=session.getServletContext();
//获取服务器中文件的真实路劲
StringrealPath=servletContext.getRealPath("/static/img/cake.jpg");
//创建输入流
FileInputStreamstream=newFileInputStream(realPath);
//创建字节数组
//stream.available()获取文件中的字节数
byte[] bytes=newbyte[stream.available()];
//将流读到字节数组中
stream.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String,String>headers=newHttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition","attachment;filename=cake.jpg");
//设置响应状态码
HttpStatusstatus=HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]>responseEntity=newResponseEntity<>(bytes, headers, status);
stream.close();
returnresponseEntity;
}