Spring Boot 处理文件上传和下载 REST方式处理文件服务

测试用例

	@Test
	public void whenUploadSuccess() throws Exception {
		String result = mockMvc.perform(fileUpload("/file")
				.file(new MockMultipartFile("file", "test.txt", "multipart/form-data", "hello upload".getBytes("UTF-8"))))
				.andExpect(status().isOk())
				.andReturn().getResponse().getContentAsString();
		System.out.println(result);
	}

上传实现

public class FileInfo {
	public FileInfo(String path){
		this.path = path;
	}
	private String path;
	}
	private String folder = "/Users/zhailiang/controller";

	@PostMapping
	public FileInfo upload(MultipartFile file) throws Exception {
		System.out.println(file.getName()); //file
		System.out.println(file.getOriginalFilename());
		System.out.println(file.getSize());
		File localFile = new File(folder, new Date().getTime() + ".txt");
		file.transferTo(localFile);
		return new FileInfo(localFile.getAbsolutePath());
	}

下载实现

	@GetMapping("/{id}")
	public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {

		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);
			outputStream.flush();
		} 
//try括号后的流会自动释放
	}

		
			commons-io
			commons-io
		

response.setContentType(“application/x-download”);
response.addHeader(“Content-Disposition”, “attachment;filename=test.txt”);

你可能感兴趣的:(工具类)