文件上传与下载
本质上文件的上传与下载都是在对io流进行操作
文件上传
web.xml
<multipart-config>
<!-- 设置单个支持最大文件的大小 -->
<max-file-size>1024</max-file-size>
<!-- 设置整个表单所有文件上传的最大值 -->
<max-request-size>10240</max-request-size>
<!-- 设置最小上传文件大小 -->
<file-size-threshold>0</file-size-threshold>
</multipart-config>
@PostMapping("fileup")
public String fileup(@RequestParam("fileName") MultipartFile multipartFile){
// MultipartFile是springmvc专门为文件上传创建的类,这个类可以看作是传送的文件
// 获取文件名称
String originalFilename=multipartFile.getOriginalFilename();
// 对该文件的操作同javase中对文件的操作
// 输入流
InputStream in = multipartFile.getInputStream();
// 封装成带缓存的输入流
BufferedInputStream bis = new BufferedInputStream(in);
//输出流
ServletContext application = request.getServletContext();
String realPath = application.getRealPath("/upload");
File file = new File(realPath)
if(!file.exists()){
file.mkdirs();
}
// 这里可能会出现上传同名文件出现的覆盖问题,可以用UUID代替文件名
// File destFile = new File(file.getAbsolutePath()+"/"+originalFilename);
File destFile = new File(file.getAbsolutePath()+"/"+UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf(".")));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
// 边读边写
byte[] bytes = new byte[1024*10];
int readCount = 0;
while((readCount = bis.read(bytes)) != -1){
bos.write(bytes,0,readCount);
}
bos.flush();
bos.close();
bis.close();
return "success"
}
<!-- enctype用于设置请求头内容默认是application/x-www-form-urlencoded -->
<form th:action="@{/fileup}" method="post" enctype="multipart/form-data">
文件:<input type="file" name="fileName" />
<input type="submit" value="上传" />
</form>
文件下载
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile(HttpServletResponse response,HttpServletRequest request) throws IOException {
File file = new File(request.getServletContext().getRealPath("/upload") + "/1.jpeg");
// 创建响应头对象
HttpHeaders headers = new HttpHeaders();
// 设置响应内容
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 设置下载文件的名字
headers.setContentDispositionFormData("attachment", file.getName());
// 下载文件
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(Files.readAllBytes(file.toPath()),headers,HttpStatus.OK);
return entity;
}
<a th:hreaf="@{/download}">文件下载</a>