SpringBoot#Download
_amaze!
如果不使用fastdfs等分布式的文件存储,有时候还是需要上传文件到web应用所在的服务器的磁盘上,下载文件。下面是一个小demo,关于如何用控制器进行上传和下载。
-
@PostMapping(value="/upload",produces="application/json; charset=utf-8") @ResponseBody public String upload(@RequestParam(value="file", required=false) MultipartFile file, HttpServletRequest req) { //String t = req.getContentType(); //System.out.println("content type :"+t); String filePath = "c:/upload/"; if (file == null) { return "200"; } String fileName = file.getOriginalFilename(); File dest = new File(filePath + fileName); try { file.transferTo(dest); System.out.println("上传成功:"+dest.getAbsolutePath()); return "上传成功:"+dest.getAbsolutePath(); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); } return "上传失败!"+e.getLocalizedMessage(); } @RequestMapping("/download/xxxx/{uid}") public String downLoad2(HttpServletResponse response, @PathVariable long uid){ String filename=uid+"_front.png"; File file = xxxxService.xxxxMethod(uid); if(file.exists()){ //判断文件父目录是否存在 response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;fileName=" + filename); byte[] buffer = new byte[1024]; FileInputStream fis = null; //文件输入流 BufferedInputStream bis = null; OutputStream os = null; //输出流 try { os = response.getOutputStream(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); int i = bis.read(buffer); while(i != -1){ os.write(buffer); i = bis.read(buffer); } } catch (Exception e) { e.printStackTrace(); } System.out.println("----------file download:" + filename); try { bis.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
-