Springmvc fileupload上传

来源:互联网 发布:unity3d 阴影锯齿 编辑:程序博客网 时间:2024/06/16 22:49

1、springmvc.xml必须配置: <bean id="multipartResolver"   class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/>   

2、 WEB-INF/lib下必加入:commons-fileupload.jar与commons-io-1.4.jar二个文件  

3、 表单属性为: enctype="multipart/form-data"

4、其中重要的代码如下:

@RequestMapping(value = "/upload", method = RequestMethod.POST)public ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response, BindException errors)throws Exception {MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");String name = multipartRequest.getParameter("name");System.out.println("name: " + name);// 获得文件名:String realFileName = file.getOriginalFilename();System.out.println("获得文件名:" + realFileName);// 获取路径String ctxPath = request.getSession().getServletContext().getRealPath("/")+ "images/";// 创建文件File dirPath = new File(ctxPath);if (!dirPath.exists()) {dirPath.mkdir();}File uploadFile = new File(ctxPath + realFileName);FileCopyUtils.copy(file.getBytes(), uploadFile);return new ModelAndView("success");}@RequestMapping(value = "/upload2", method = RequestMethod.POST)public ModelAndView onSubmit2(HttpServletRequest request,HttpServletResponse response, BindException errors)throws Exception {// 转型为MultipartHttpRequestMultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;// 根据前台的name名称得到上传的文件MultipartFile file = multipartRequest.getFile("file");// 获得文件名:String realFileName = file.getOriginalFilename();// 获取路径String ctxPath = request.getSession().getServletContext().getRealPath("/")+ "\\" + "images\\";// 创建文件File dirPath = new File(ctxPath);if (!dirPath.exists()) {dirPath.mkdir();}File uploadFile = new File(ctxPath + realFileName);FileCopyUtils.copy(file.getBytes(), uploadFile);return new ModelAndView("success");}@RequestMapping(value = "/upload3", method = RequestMethod.POST)public String upload(@RequestParam("file")MultipartFile image, HttpServletRequest request) throws IOException {String ctxPath = request.getSession().getServletContext().getRealPath("/")+ "\\" + "images\\";System.out.println("路径:" + ctxPath);File file = new File(ctxPath + "/" + image.getOriginalFilename());// FileCopyUtils.copy(image.getBytes(),new// File(ctxPath+"/"+image.getOriginalFilename()));try {image.transferTo(file); // 保存上传的文件} catch (IllegalStateException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return "success";}// 多文件上传@RequestMapping(value = "/upload4", method = RequestMethod.POST)public ModelAndView fileUpload(HttpServletRequest request,HttpServletResponse response, BindException errors)throws Exception {MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();String ctxPath = request.getSession().getServletContext().getRealPath("/")+ "\\" + "images\\";File file = new File(ctxPath);if (!file.exists()) {file.mkdir();}String fileName = null;for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {// 上传文件名// System.out.println("key: " + entity.getKey());MultipartFile mf = entity.getValue();fileName = mf.getOriginalFilename();File uploadFile = new File(ctxPath + fileName);FileCopyUtils.copy(mf.getBytes(), uploadFile);}return new ModelAndView("success");}


@RequiresPermissions(value={"vote:voteQuestion:add","vote:voteQuestion:edit"},logical=Logical.OR)@RequestMapping(value = "save")public String save(VoteQuestion voteQuestion, VoteOption voteOption, String question, String vid, String allowUserInput,@RequestParam(value = "file", required = false) MultipartFile[] file, Model model, RedirectAttributes redirectAttributes) throws Exception{if (!beanValidator(model, voteQuestion)){return form(voteQuestion, voteOption, null, null, null, model);}//获取外部地址Properties properties = new Properties();InputStream in = Object.class.getResourceAsStream("/runyu.properties");String param = "";try {properties.load(in);param = properties.getProperty("ExternalURL").trim();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}// 文件保存路径:webapp/年-月String path = Global.getDirPath()+ "/" +DateUtils.getYear() + "-"+ DateUtils.getMonth()+ "/";  // 构建图片保存的目录File pathfile = new File(path); if (!pathfile.exists()) { //如果文件夹不存在pathfile.mkdirs(); //创建}if(!voteQuestion.getIsNewRecord()){//编辑表单保存VoteQuestion t = voteQuestionService.get(voteQuestion.getId());//从数据库取出记录的值t.setVid(vid);if("允许".equals(allowUserInput)){t.setAllowUserInput("其他");}else if("禁止".equals(allowUserInput)){t.setAllowUserInput(null);}MyBeanUtils.copyBeanNotNull2Bean(t, voteQuestion);//将编辑表单中的非NULL值覆盖数据库记录中的值voteQuestionService.save(t);//保存List<VoteOption> list =voteOption.getSq(); //获取前台所有动态添加的数据if(list.size()>0 && list!=null){for (int i = 0; i < list.size(); i++) {VoteOption vOption = list.get(i);vOption.setVid(vid);vOption.setQid(voteQuestion.getQid());vOption.setOid(IdGen.uuid());// 保存try {if(null != file && file.length > 0){  int j = 0; //定义一个变量            //遍历并保存文件              for(MultipartFile file2 : file){             if(i==j){ //如果i=j,逐个遍历获取图片文件            String fileName1 = file2.getOriginalFilename(); //获取文件名String extensionName = fileName1.substring(fileName1.lastIndexOf(".") + 1);//获取文件名if (!"".equals(extensionName)) { //如果名称不为空String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName; //获取一个新的文件名称vOption.setPicture(param + "a/vote/voteQuestion/ReadAddress" +"?imgUrl=" + newFileName); //赋值file2.transferTo(new File(path + newFileName));  }            }            j++; //每次循环,j加1            }          }  } catch (Exception e) {e.printStackTrace();}MyBeanUtils.copyBeanNotNull2Bean(vOption, voteOption);//将编辑表单中的非NULL值覆盖数据库记录中的值voteOptionService.save(vOption);//保存}}}else{//新增表单保存voteQuestion.setVid(vid);voteQuestion.setQid(IdGen.uuid());voteQuestion.setQuestion(question);if("允许".equals(allowUserInput)){voteQuestion.setAllowUserInput("其他");}else if("禁止".equals(allowUserInput)){voteQuestion.setAllowUserInput(null);}voteQuestionService.save(voteQuestion);//保存List<VoteOption> list =voteOption.getSq(); //获取前台所有动态添加的数据if(list.size()>0 && list!=null){for (int i = 0; i < list.size(); i++) {VoteOption vOption = list.get(i);vOption.setVid(vid);vOption.setQid(voteQuestion.getQid());vOption.setOid(IdGen.uuid());// 保存try {if(null != file && file.length > 0){  int j = 0;            //遍历并保存文件              for(MultipartFile file2 : file){             if(i==j){            String fileName1 = file2.getOriginalFilename(); //获取文件名String extensionName = fileName1.substring(fileName1.lastIndexOf(".") + 1);//获取文件名if (!"".equals(extensionName)) { //如果名称不为空String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName; //获取一个新的文件名称vOption.setPicture(param + "a/vote/voteQuestion/ReadAddress" +"?imgUrl=" + newFileName); //赋值file2.transferTo(new File(path + newFileName));  }            }            j++;            }          }  } catch (Exception e) {e.printStackTrace();}MyBeanUtils.copyBeanNotNull2Bean(voteOption, vOption);//将编辑表单中的非NULL值覆盖数据库记录中的值voteOptionService.save(vOption);//保存}}else{System.out.println("空值");}}String lmtID = "";//定义VoteMainTitle id编码变量List<VoteMainTitle> lvMainTitles = voteMainTitleService.getVid(vid);//根据vid编码查询遍历VoteMainTitle表if(lvMainTitles.size()>0 && lvMainTitles!=null){for (int i = 0; i < lvMainTitles.size(); i++) {VoteMainTitle vTitle = lvMainTitles.get(i);//获取遍历对象lmtID = vTitle.getId(); //获取VoteMainTitle id编码}}addMessage(redirectAttributes, "保存问题成功");return "redirect:"+Global.getAdminPath()+"/vote/voteMainTitle/form?id="+lmtID+"&isAdd=1";}

0 0
原创粉丝点击