我正在尝试在我的网络应用程序中添加文件上传和下载。
当我使用spring mvc时,我习惯不使用原始HttpServletRequest
和HttpServletResponse
。但现在我有跟随控制器下载文件。
public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws Exception {
int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
Files file = this.filesService.find(id);
response.setContentType(file.getType());
response.setContentLength(file.getFile().length);
response.setHeader("Content-Disposition","attachment; filename=\"" + file.getFilename() +"\"");
FileCopyUtils.copy(file.getFile(), response.getOutputStream());
return null;
}
如您所见,我在此处使用HttpServletRequest
和HttpServletResponse
。
我想找到避免使用这些类的方法。有可能吗?
答案 0 :(得分:0)
您从id
获取的request
参数可以替换为使用@RequestParam
或@PathVariable
。有关@RequestParam
public ModelAndView download(@RequestParam("id") int id) {
// Now you can use the variable id as Spring MVC has extracted it from the HttpServletRequest
Files file = this.filesService.find(id); // Continue from here...
}
现在是响应部分
@RequestMapping(value = "/download")
public ResponseEntity<byte[]> download(@RequestParam("id") int id) throws IOException
{
// Use of http headers....
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
InputStream is // Get your file contents read into this input stream
return new ResponseEntity<byte[]>(IOUtils.toByteArray(is), headers, HttpStatus.CREATED);
}