Spring中文件下载相当的简单,只需要以下几行代码。需要注意的是文件名如果包含中文等,需要URLEncoder转码。
@Controller
public class TestDownloadController {
@RequestMapping("/basic/download")
public ResponseEntity<byte[]> fileDownload(String filename, HttpServletRequest request) throws IOException {
File file = new File("C:\\download\\" + filename);
if (!file.exists()) {
return null;
}
filename = URLEncoder.encode(filename, "UTF-8");
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
}
}