###spring mvc 文件上传下载
####上传
-
用MultipartFile来上传文件,上传到本地指定路径下
-
controller:
@RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file, @RequestParam("type") Integer type, HttpServletRequest request, HttpServletResponse response) { Preconditions.checkNotNull(type); Preconditions.checkNotNull(file); Preconditions.checkArgument(file.getSize() < Constants.FILE_MAX_SIZE); Preconditions.checkArgument(Constants.FILE_TYPE_MAP.containsKey(type)); if (!this.validate(file)) { return JsonReply.newItem().failed().toJson(); } String path = request.getSession().getServletContext().getRealPath("/"); Long fileId = fileService.saveFile(file, type, path); if (fileId.equals(Constants.ERROR_LONG)) { return JsonReply.newItem().failed().toJson(); } JsonReply reply = JsonReply.newItem(); reply.addObject("id", fileId); return reply.success().toJson(); }
type是对类型做一个分类,不同类别放到不同文件夹下
-
service:
@Override public Long saveFile(@NonNull MultipartFile multipartFile, Integer type, String path) { // TODO Auto-generated method stub String originalName = multipartFile.getOriginalFilename(); // String fileDir = path + originalName; String fileDir = Constants.FILE_DIR + Constants.FILE_TYPE_MAP.get(type) + originalName; final File file = new File(fileDir); try { Files.write(multipartFile.getBytes(), file); } catch (IOException e) { // TODO: handle exception log.info("save file error,{}", e); return Constants.ERROR_LONG; } FileBo fileBo = new FileBo(); fileBo.setUrl(originalName); fileBo.setType(type); fileDao.saveFileInfo(fileBo); return fileBo.getId();
}
-
前端:
#####下载
-
用HttpServletResponse来下载,但是不是最好的选择,今后改
-
controller:
@RequestMapping(value = "/download/{id}") public void file(@PathVariable Long id, HttpServletResponse resp) throws IOException { OutputStream output = resp.getOutputStream(); Preconditions.checkNotNull(id); FileBo file = fileService.getFileBo(id); if (file == null) { return; } String disposition = "attachment;filename=" + file.getUrl(); resp.reset(); resp.setHeader("Content-Disposition", disposition); resp.setContentType("application/octet-stream; charset=utf-8"); try { fileService.download(file, output); } catch (IOException e) { // TODO: handle exception log.info("FileController.file failed.[{e}]", e); } finally { IOUtils.closeQuietly(output); } }
-
service
@Override public void download(FileBo file, OutputStream output) throws IOException { // TODO Auto-generated method stub String fileDir = Constants.FILE_DIR + Constants.FILE_TYPE_MAP.get(file.getType()) + file.getUrl(); final File downloadFile = new File(fileDir); output.write(FileUtils.readFileToByteArray(downloadFile)); }