springmvc上传下载代码

  1 /**
  2  * Created by ${huangjianbo} on 2017/7/12 0012.
  3  */
  4 @Controller
  5 @RequestMapping("/index")
  6 public class IndexController extends BaseController{
  7     @Resource(name = "goodsService")
  8     private GoodsService goodsService;
  9     @Resource(name = "imageService")
 10     private ImageService imageService;
 11     @RequestMapping("/index")
 12     public String index(){
 13         return "home";
 14     }
 15     @RequestMapping("/list")
 16     public String list(ModelMap model){
 17         List<GoodsEntity> list = goodsService.queryAll();
 18         model.addAttribute("list",list);
 19         return "list";
 20     }
 21     /**
 22      * 上传1
 23      * @param request
 24      * @return
 25      * @throws IOException
 26      */
 27     @RequestMapping(value = "/upload",method = RequestMethod.POST)
 28     public String upload(ModelMap model,HttpServletRequest request) throws IOException {
 29         // 得到CommonsMultipartResolver对象
 30         CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
 31                 request.getSession().getServletContext());
 32         // 判断 request 是否有文件上传,即多部分请求
 33         if (multipartResolver.isMultipart(request)) {
 34             // 转换成多部分request
 35             MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
 36             // 取得request中的所有文件名
 37             Iterator<String> iter = multiRequest.getFileNames();
 38             while (iter.hasNext()) {
 39                 // 取得上传文件
 40                 MultipartFile f = multiRequest.getFile(iter.next());
 41                 if (f != null) {
 42                     // 取得当前上传文件的文件名称
 43                     String myFileName = f.getOriginalFilename();
 44                     // 如果名称不为“”,说明该文件存在,否则说明该文件不存在
 45                     if (myFileName.trim() != "") {
 46                         // 定义上传路径
 47                         String path = request.getSession().getServletContext().getRealPath("upload");
 48                         String p = Thread.currentThread().getContextClassLoader().getResource("").getPath();
 49                         File localFile = new File(path, myFileName);
 50                         if(!localFile.exists()){        //不存在文件夹,创建
 51                             localFile.mkdirs();
 52                         }
 53                         f.transferTo(localFile);
 54                         ImageEntity imageEntity = new ImageEntity();
 55                         String x = "file:///"+path+"\\"+f.getOriginalFilename();
 56                         x.substring(39);
 57                         imageEntity.setImage(x.substring(39));
 58                         System.out.println("file:///"+path+"\\"+f.getOriginalFilename());
 59                         imageService.insert(imageEntity);
 60                         model.addAttribute("imageEntity",imageEntity);
 61                     }
 62                 }
 63 
 64             }
 65         }
 66         return "success";
 67     }
 68 
 69     /**
 70      * 下载
 71      * @param fileName 文件名称
 72      * @param request
 73      * @param response
 74      * @throws Exception
 75      */
 76     @RequestMapping("/download/{fileName:.+}")
 77     public void download(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
 78 
 79         BufferedInputStream bis = null;
 80         BufferedOutputStream bos = null;
 81         //获取下载文件路径
 82         String downLoadPath = request.getSession().getServletContext().getRealPath("upload")+"\\" + fileName;
 83         //获取文件的长度
 84         long fileLength = new File(downLoadPath).length();
 85         //设置文件输出类型
 86         response.setHeader("Content-disposition", "attachment; filename="
 87                 + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
 88         //设置输出长度
 89         response.setHeader("Content-Length", String.valueOf(fileLength));
 90         //获取输入流
 91         bis = new BufferedInputStream(new FileInputStream(downLoadPath));
 92         //输出流
 93         bos = new BufferedOutputStream(response.getOutputStream());
 94         byte[] buff = new byte[2048];
 95         int bytesRead;
 96         while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
 97             bos.write(buff, 0, bytesRead);
 98         }
 99         //关闭流
100         bis.close();
101         bos.close();
102     }

 

posted @ 2017-07-28 09:49  Hjianbo  阅读(117)  评论(0编辑  收藏  举报