文件上传
创建FileInfo返回对象
public class FileInfo implements Serializable {
private String path;
public FileInfo(String path) {
this.path = path;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
创建文件上传controller
@RestController
@RequestMapping("/file")
public class FileController {
@PostMapping
public FileInfo upload(MultipartFile file) throws IOException {
System.out.println(file.getName());
System.out.println(file.getOriginalFilename());
System.out.println(file.getSize());
String folder = "D:\\workspace\\whale-security\\whale-security-demo\\src\\main\\java\\com\\whale\\web\\controller";
File localFile = new File(folder,new Date().getTime()+".txt");
//file.getInputStream() 也可以获取到文件流用阿里so上传
file.transferTo(localFile);//写到本地文件
return new FileInfo(localFile.getAbsolutePath());
}
}
测试
@Test
public void whenUploadSuccess() throws Exception {
String result = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/file") //是post请求
.file(new MockMultipartFile("file","test.txt","multipart/form-data","hello upload".getBytes("utf-8"))))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
运行控制台打印:
下载
加入处理流的依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version></version>
</dependency>
下载方法 get请求
@GetMapping("{id}")
public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response){
//jdk1.7语法 将流声明在try() 可以自动关闭
try(
InputStream inputStream = new FileInputStream(new File(folder,id+".txt"));
OutputStream outputStream = response.getOutputStream();
) {
response.setContentType("application/x-download");
response.addHeader("Content-Disposition","attachment;filename=test.txt");//下载文件名称
IOUtils.copy(inputStream,outputStream);//输入流copy到输出流
outputStream.flush();
}catch (Exception e){
e.printStackTrace();
}
}