uploadFile & downloadFile

@RestController
@RequestMapping("/file")
public class FileController {
	private String folder = "/Users/zhailiang/Documents/my/muke/inaction/java/workspace/github/fkandy-security-demo/src/main/java/com/fkandy/web/controller";
	@PostMapping
	public FileInfo upload(MultipartFile file) throws Exception {
		System.out.println(file.getName());
		System.out.println(file.getOriginalFilename());
		System.out.println(file.getSize());
		File localFile = new File(folder, new Date().getTime() + ".txt");
        //save into the currently folder
		file.transferTo(localFile);
        //file.getInputStream() for remote server
		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");
			//FileCopyUtils.copy same with IOUtils.copy
             IOUtils.copy(inputStream, outputStream);
			outputStream.flush();
		} 
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章