Springmvc fileupload上传

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 {

		// 转型为MultipartHttpRequest
		MultipartHttpServletRequest 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 exception
			e.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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值