SpringMvc 图片上传功能

来源:互联网 发布:环信java服务器端搭建 编辑:程序博客网 时间:2024/05/20 01:09

因为工作中有遇到图片文件上传功能,所以随手简单记录下,


1.首先前端页面打包文件

1).jsp页面代码:

 <form action="/backImage.do" method="post" enctype="multipart/form-data">     选择文件:<input type="file" name="file">     <input type="submit" value="上传"> </form>

2.设置applicationContext.xml 中限制上传文件的大小

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">   <property name="maxUploadSize" value="10485760"/>   <property name="defaultEncoding" value="utf-8"/></bean>


3.Controller接口:单张图片上传及多张图片上传

1.单张图片上传:

@Transactional   @ResponseBody   @RequestMapping(value = "backImage.do", method = {RequestMethod.POST })   public JSONObject backImage(@RequestParam MultipartFile file,         @RequestParam Map<String,String> map,         HttpServletRequest request, HttpServletResponse response,         HttpSession session){      logger.info("进入背景图上传接口.....");      JSONObject jsonMap = JSONObject.parseObject(map.get("Data"));      JSONObject js = new JSONObject();      JSONObject resultJs = new JSONObject();      String uuid = "";      // 保存文件      try {         js = ImgUpload.imgUp(file, request, response, session,"/hzimgs");         logger.info("背景图上传服务器成功.....");         if(js.getBooleanValue("flag")){            //上传成功,先用手机号码查询用户ID判断该用户是否有上传过log,有就更新,没有就新增.            Map<String,Object> userMap = new HashMap<String,Object>();            userMap.put("userPhone", jsonMap.getString("mobilePhone"));            System.out.println(jsonMap.getString("mobilePhone"));//          userMap.put("userPhone", "18601");            SysUser sysUser = regDao.findUserForCon(userMap);            boolean identityIdExists =false;                     //user identity_id 存在则不使用新的identity_id            if(sysUser.getIdentityId()!=null){               if(sysUser.getIdentityId().length()>0){                  identityIdExists = true;               }            }            if(identityIdExists){            uuid =sysUser.getIdentityId();            }else{                uuid = SoleCode.getGUID();                regDao.upIdentityForPhone(sysUser.getUserPhone(), uuid);            }                        Map<String,Object> findMap = new HashMap<String,Object>();            findMap.put("identity_id", uuid);            findMap.put("type", "HzBack");            SysImgs sysImg = null;            try {               sysImg = imgDao.findImgForCon(findMap);            } catch (Exception e){               resultJs = this.getJsonData("", "上传图片查找对象失败!", false, js);            }               if(sysImg == null){                  //新增                  Map<String,Object> addMap = new HashMap<String,Object>();                  SysImgs img = new SysImgs();                  img.setCreateTime(new Date());                  img.setCreateUser(sysUser.getId());                  img.setFileName(js.getString("fileName"));                  img.setIdentityId(uuid);                  img.setIsDel(0);                  img.setPath(js.getString("path"));                  img.setReason("");                  img.setStatus(0);                  img.setType("HzBack");                  img.setUpdateTime(null);                  img.setUpdateUser(0);                  addMap.put("img", img);                  try{                     imgDao.addImg(addMap);                     logger.info("背景图上传数据库成功.....");                     resultJs = this.getJsonData("","OK",true,js);                  } catch (Exception e){                     resultJs = this.getJsonData("","图片新增失败!",false,js);                  }               } else {                  //更新TODO                  Map<String,Object> updateMap = new HashMap<String,Object>();                  updateMap.put("fileName", js.getString("fileName"));                  updateMap.put("path", js.getString("path"));                  updateMap.put("updateUser", sysUser.getId());                  updateMap.put("updateTime", new Date());                  updateMap.put("createUser", sysUser.getId());                  updateMap.put("imgType", "HzBack");                  try{                     imgDao.updateImg(updateMap);                     ImgDelectFile.deleteFileOrDirectory(request,sysImg.getFileName(), sysImg.getPath());                     logger.info("更新背景图上传数据库成功.....");                     resultJs = this.getJsonData("", "OK", true, js);                  } catch(Exception e){                     resultJs = this.getJsonData("", "logo更新失败!", false, js);                  }               }                     } else {            //上传失败            resultJs = this.getJsonData("", "图片读取上传失败!", false, js);                     }      } catch (IllegalStateException e) {         resultJs = this.getJsonData("", "图片读取失败!", false, js);               } catch (IOException e) {         resultJs = this.getJsonData("", "图片读取失败!", false, js);      }      logger.info("背景图上传  the end.....");      return resultJs;   }

2).多张图片上传:

@Transactional   @ResponseBody   @RequestMapping(value="sendArticle.do", method={RequestMethod.POST,RequestMethod.GET})   public JSONObject sendArticle(@RequestParam Map<String,String> map,         @RequestParam MultipartFile[] file,         HttpServletRequest request, HttpServletResponse response,         HttpSession session)               throws IllegalStateException, IOException{      logger.info("进入朋友圈消息接口.............");      JSONObject jsonMap = JSONObject.parseObject(map.get("Data"));      SysFriends sf = new SysFriends();      JSONObject jsonObj = new JSONObject();      Long friendId = 0L;//发表动态的id      String uuid = SoleCode.getGUID();      String content = jsonMap.getString("content");      String phone = jsonMap.getString("mobilePhone");//    String content = request.getParameter("content");//    String phone = "18601";      logger.info("进入朋友圈消息接口 数据解析成功............."+jsonMap+"....phone=="+phone);      //前端还需要发送登录者的信息,根据手机号查找用户ID      Map<String,Object> userMap = new HashMap<String,Object>();      userMap.put("userPhone", phone);      SysUser sysUser = regDao.findUserForCon(userMap);      logger.info("查询数据............"+sysUser.toString());      //插入朋友圈表      if(sysUser != null){         Map<String,Object> sfMap = new HashMap<String,Object>();         sf.setContent(content);         sf.setCreateTime(new Date());         sf.setCreateUser(sysUser.getId());         sf.setErpId(Integer.parseInt(jsonMap.getString("erpId")));         sf.setErpId(1);         sf.setIdentityId(uuid);         sf.setIsDel(0);         sf.setSource(null);         sf.setSysUserId(sysUser.getId());         sf.setUpdateTime(null);         sf.setUpdateUser(0);         sf.setStatus(0);         sf.setReason("");         sfMap.put("sf", sf);         logger.info("插入朋友圈消息start.............");         try{            sfDao.addFriendArticle(sfMap);            friendId = (Long) sfMap.get("id");//每一条动态的ID            sf.setId(friendId.intValue());            logger.info("插入朋友圈消息成功.............");         } catch(Exception e){//          jsonObj.put("MSG_CODE", "发表动态失败!");//          jsonObj.put("Data","");//          jsonObj.put("Result", false);            jsonObj = this.getJsonData("", "发表动态失败!", false, jsonObj);            logger.info("插入朋友圈消息失败.............");            return jsonObj;         }      }

这里多张图片上传功能做的是一个朋友圈的发表心情动态的功能。


说明:这里包含了Mybatis对数据库操作,你们可以自己攫取所需要的东西。另外 :@RequestParam MultipartFile file 这种写法可以与android端适用,

如果写成:@RequestParam(value="file") MultipartFile file  这样写针对web端是没有任何问题的,但针对移动端就会有问题,移动端请求会进不来。


4.imgUp:上传图片至服务端的工具类---->这里分为多张图片上传与单张图片上传的工具类

1.单张图片上传:

public static JSONObject imgUp(MultipartFile file, HttpServletRequest request,      HttpServletResponse response, HttpSession session,String filepath) throws IllegalStateException, IOException {   JSONObject js = new JSONObject();      if(file != null){      String path = null;//文件路劲      String type = null;//文件类型      String fileName = file.getOriginalFilename();//文件名      type = fileName.indexOf(".") != -1?fileName.substring(fileName.lastIndexOf(".")+1,fileName.length()):null;      if(type != null){         if("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())){            // 项目在容器中实际发布运行的根路径                  String realPath= request.getSession().getServletContext().getRealPath("/").concat("../slswappfiles")+filepath;                  System.out.println(realPath);               // 自定义的文件名称                     String trueFileName =new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+fileName;                  // 设置存放图片文件的路径                   path=realPath+System.getProperty("file.separator")+trueFileName;                   System.out.println("存放图片文件的路径:"+path);                   File targetFile = new File(realPath,trueFileName);                   if (!targetFile.exists()) {                       targetFile.mkdirs();                   }                    // 转存文件到指定的路径                    file.transferTo(targetFile);                                       js.put("path", "/slsw"+filepath+"/");                    js.put("fileName", trueFileName);                    js.put("flag", true);         }else {                   System.out.println("不是我们想要的文件类型,请按要求重新上传");                   js.put("flag", false);                   return js;                }      }else{           System.out.println("文件类型为空");           js.put("flag", false);                return js;      }   }else {           System.out.println("没有找到相对应的文件");           js.put("flag", false);           return js;          }   return js;}

  这里只提供本人项目所用的东西,你们只要截取你们所需就ok


2.多张图片上传:

public static JSONObject imageUploa(MultipartFile[] file,      HttpServletRequest request, HttpServletResponse response,      HttpSession session)      throws IllegalStateException, IOException {   JSONObject jsonObj = new JSONObject();   JSONObject js = new JSONObject();   List<SysImgs> list = new ArrayList<SysImgs>();   SysImgs sImg = null;   // String images = imageUtil.ImageUpload(file,   // request,response,session);   if (file != null && file.length > 0) {      // 循环获取file数组中得文件      for (int i = 0; i < file.length; i++) {         MultipartFile files = file[i];                    // 保存文件         jsonObj = ImgUpload.imgUp(files, request, response,               session,"/upload");                  if(jsonObj.getBooleanValue("flag")){            sImg = new SysImgs();            sImg.setPath((String) jsonObj.get("path"));                        sImg.setFileName((String) jsonObj.get("fileName"));                        System.out.println((String) jsonObj.get("fileName"));            list.add(sImg);                     } else {                        continue;         }               }      js.put("list", list);   }   return js;}



原创粉丝点击