文件上传
@Test
public void whenUploadSuccess() {
try {
String file = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/file")
.file(new MockMultipartFile("file", "test.txt",
"multipart/form-data", "hello upload".getBytes("UTF-8"))))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
log.info("file:{}",file);
} catch (Exception e) {
e.printStackTrace();
}
}
@PostMapping
public FileInfo upload(MultipartFile file) {
log.info(file.getName());
log.info(file.getOriginalFilename());
log.info(String.valueOf(file.getSize()));
File localFile = new File(folder, new Date().getTime() + ".txt");
try {
file.transferTo(localFile);
return new FileInfo(localFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
文件下载
@GetMapping("/{id}")
public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
try (InputStream ips = new FileInputStream(new File(folder, id + ".txt"));
OutputStream ops = response.getOutputStream();) {
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename=test.txt");
IOUtils.copy(ips, ops);
ops.flush();
}catch (IOException e){
e.printStackTrace();
}
}
网友评论