springmvc的单文件上传

  @RequestMapping("/up")
  public ModelAndView up(MultipartFile myfiles , HttpServletRequest request){
    ModelAndView model = new ModelAndView();
    String result = savePic(request, myfiles);  //调用保存的方法
    if(!StringUtils.isEmpty(result)){      --非必要代码
      System.out.println("上传成功!");
      model.addObject("fileName",result);
      model.setViewName("/picshow");
    }else{
      System.out.println("上传失败!");
    }
    return model;
  }

  public String savePic(HttpServletRequest request,MultipartFile multipartFile){
    try {
      if(!multipartFile.isEmpty()){
        String filePath = request.getServletContext().getRealPath("upPic");  //获取upPic文件夹的路径
        String fileName =new Date().getTime()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."),         multipartFile.getOriginalFilename().length());             
        String newFileName = filePath+File.separator+fileName;
        File file = new File(newFileName);                   //创建文件对象
        if(!file.getParentFile().exists()){                    //不存在父路径进行创建
          file.getParentFile().mkdir();
        }
        multipartFile.transferTo(file);                     //进行文件转存
        return fileName;                           //返回存储的文件的名称
      }
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

posted @ 2016-09-05 20:21  西风恶  阅读(289)  评论(0编辑  收藏  举报