spring mvc那些破事儿

 

1:使用SpringMVC 实现批量上传

报错:**.SecurityContextHolderAwareRequestWrapper can not be cast to **.DefaultMultipartHttpServletRequest

使用springmvc上传要加上

 

<bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”>
	<property name="maxUploadSize" value="400000" />
</bean>

Action处理

 

@RequestMapping(value = "/upload.htm")
	public static void uploadmutiFiles(HttpServletRequest req,
			HttpServletResponse res, ModelAndView model) {
		String path = req.getSession().getServletContext()
				.getRealPath("/upload/"); // 获取本地存储路径
		MultipartHttpServletRequest mul = (MultipartHttpServletRequest) req;
		List<MultipartFile> files = mul.getFiles("file");
		String msg = "上传成功";
		try {
			for (int i = 0; i < files.size(); i++) {
				CommonsMultipartFile mf = (CommonsMultipartFile) files.get(i);
				File file = new File(path + "/" + mf.getOriginalFilename());
				int index = mf.getOriginalFilename().lastIndexOf(".");
				String filename = mf.getOriginalFilename().substring(0, index);
				String extendname = mf.getOriginalFilename().substring(index);
				int ex = 1;
				while (file.exists()) {
					file = new File(path + "/" + filename + "(" + ex + ")" + extendname);
					ex++;
				}
				mf.getFileItem().write(file);
			}
		} catch (Exception e) {
			msg = "上传失败";
			e.printStackTrace();
		}
		try {
			res.getWriter().print(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

2  but   kindeditor 编辑器就不可用了,因为编辑器用的一般的上传,spring mvc上传的话request 就不是一般性的http协议请求,而编辑器用的是普通http协议传输的HttpServletRequest,如果用编辑器默认的上传代码,这样的话报错会反过来,会自动的转换成MultipartHttpServletRequest,转换报错.

 

  解决办法: 去掉那<bean>配置,修改上传方法,注意表单中file的name属性值与mul.getFiles("xxx");  一一对应

,否则文件无法获取

 

	public static void uploadmutiFiles(HttpServletRequest request,
			HttpServletResponse res, ModelAndView model) {
		CommonsMultipartResolver commonsMultipartResolver = new   
			CommonsMultipartResolver(request.getSession().getServletContext());  
		commonsMultipartResolver.setDefaultEncoding("utf-8");  
		String path = request.getSession().getServletContext().getRealPath("/upload/"); // 获取本地存储路径
		String msg = "上传成功";
		try {
			if (commonsMultipartResolver.isMultipart(request)){
				MultipartHttpServletRequest mul =  commonsMultipartResolver.resolveMultipart(request);  
				List<MultipartFile> files = mul.getFiles("file"); // 这里可以用mul.getParamter("xxxx");
				for (int i = 0; i < files.size(); i++) {
					CommonsMultipartFile mf = (CommonsMultipartFile) files.get(i);
					File file = new File(path + "/" + mf.getOriginalFilename());
					int index = mf.getOriginalFilename().lastIndexOf(".");
					String filename = mf.getOriginalFilename().substring(0, index);
					String extendname = mf.getOriginalFilename().substring(index);
					int ex = 1;
					while (file.exists()) {
						file = new File(path + "/" + filename + "(" + ex + ")" + extendname);
						ex++;
					}
					mf.getFileItem().write(file);
				}
			} 
		} catch (Exception e) {
			msg = "上传失败";
			e.printStackTrace();
		}
		try {
			res.getWriter().print(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

   问题搞定,而且和任何编辑器没任何挂噶。

3 but 一般上传form需要加上enctype="multipart/form-data",但是DTO无法获取了,参考文

   解决办法:spring mvc 多个配置 默认的web-main.xml 不加

 

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="maxUploadSize" value="1048576" />
            <property name="defaultEncoding" value="utf8" />
 </bean>

 而利用spring mvc上传文件的配置中(名字随意 如web-main-image.xml )加上它,其他的配置属性相同。

 

web.xml 配置上传的分发器,指定springmvc 配置文件位置

 

	<servlet>
		<servlet-name>springServletImage</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>WEB-INF/config/spring/web/web-main-image.xml</param-value>
		</init-param>
		<load-on-startup>2</load-on-startup>
	</servlet>

 

 不过重复的配置很烦人,web-main-image.xml 可以就把multipartResolver配置,其他配置不要,但是下面的param-value要指定默认的配置文件和web-main-image.xml两个文件,指定两个以都好分割就好了。<param-value>WEB-INF/config/spring/web/web-main.xml,WEB-INF/config/spring/web/web-main-image.xml</param-value>

 

 < textarea id="content" name = "content" value="$!{obj.content}" ></textarea>
   

 指定相应的方法约束用MultipartHttpServletRequest (只有配置这个的方法才用springmvc的上传)

 

<servlet-mapping>
    <servlet-name>springServletImage</servlet-name>  
    <url-pattern>/projectpart/mangage/xxx.htm</url-pattern>  
</servlet-mapping> 
 

   OK 配置完成,spring 对象绑定成功。上传的方法都添加一个sevlet-mapping 只是url-pattern 不同而已。

在页面层凡是上传的都必须加上enctype="multipart/form-data",否则request不是DefaultMultipartHttpServletRequest,就无法获取DTO,所以必须加上enctype属性。不能直接输入请求地址,直接输入的话还是默认的request 

4 KindEditor 使用默认的HttpServletRequest,这个也可以用MultipartHttpServletRequest,为了灵活,使用默认的HttpServletRequest 

页面调用

 

<textarea id="content" name = "content"    value="$!{obj.content}" ></textarea>

引用JS:

 

 

<script src="$!{basepath}/common/kindeditor/kindeditor-min.js"></script>
 

 

 
<script src="$!{basepath}/common/kindeditor/lang/zh_CN.js"></script>
  

编辑器调用:这个在jquery中$()里面调用,uploadJson指定相应的action的方法 

 

	KindEditor.ready(function(K) {
		var editor1 = K.create('textarea[id="content"]', {
			cssPath : appServer+'/common/kindeditor/plugins/code/prettify.css',
			uploadJson : appServer+'/xxxupload.htm',
			allowFileManager : true,
			afterCreate : function() {
				var self = this;
				K.ctrl(document, 13, function() {
					self.sync();
					document.forms['example'].submit();
				});
				K.ctrl(self.edit.doc, 13, function() {
					self.sync();
					document.forms['example'].submit();
				});
			}
		});
		prettyPrint();
	});

 Action处理: 上传方法使用编辑器默认的代码处理:

   @RequestMapping(value = "/xxxupload.htm")

	public void xxxUpload(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			// 文件保存目录路径
			String savePath = request.getRealPath("//")
					+ "//attached//xxxuploadFolder//";
			// 文件保存目录URL
			String saveUrl = request.getScheme() + "://"
					+ request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath() + "/attached/teambuy/";

			// 定义允许上传的文件扩展名
			HashMap<String, String> extMap = new HashMap<String, String>();
			extMap.put("image", "gif,jpg,jpeg,png,bmp");
			extMap.put("flash", "swf,flv");
			extMap.put("media",
					"swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
			extMap.put("file",
					"doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

			// 最大文件大小
			long maxSize = 1000000;
			response.setContentType("text/html; charset=UTF-8");
			if (!ServletFileUpload.isMultipartContent(request)) {
				out.println(getError("请选择文件。"));
				return;
			}
			// 检查目录
			File uploadDir = new File(savePath);
			if (!uploadDir.isDirectory()) {
				out.println(getError("上传目录不存在。"));
				return;
			}
			// 检查目录写权限
			if (!uploadDir.canWrite()) {
				out.println(getError("上传目录没有写权限。"));
				return;
			}
			String dirName = request.getParameter("dir");
			if (dirName == null) {
				dirName = "image";
			}
			if (!extMap.containsKey(dirName)) {
				out.println(getError("目录名不正确。"));
				return;
			}
			// 创建文件夹
			savePath += dirName + "/";
			saveUrl += dirName + "/";
			File saveDirFile = new File(savePath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String ymd = sdf.format(new Date());
			savePath += ymd + "/";
			saveUrl += ymd + "/";
			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			List items = upload.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String fileName = item.getName();
				long fileSize = item.getSize();
				if (!item.isFormField()) {
					// 检查文件大小
					if (item.getSize() > maxSize) {
						out.println(getError("上传文件大小超过限制。"));
						return;
					}
					// 检查扩展名
					String fileExt = fileName.substring(
							fileName.lastIndexOf(".") + 1).toLowerCase();
					if (!Arrays.<String> asList(extMap.get(dirName).split(","))
							.contains(fileExt)) {
						out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许"
								+ extMap.get(dirName) + "格式。"));
						return;
					}

					SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
					String newFileName = df.format(new Date()) + "_"
							+ new Random().nextInt(1000) + "." + fileExt;
					try {
						File uploadedFile = new File(savePath, newFileName);
						System.out.print(newFileName);
						item.write(uploadedFile);
					} catch (Exception e) {
						out.println(getError("上传文件失败。"));
						return;
					}

					JSONObject obj = new JSONObject();
					obj.put("error", 0);
					obj.put("url", saveUrl + newFileName);
					out.println(obj.toJSONString());
					
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(spring mvc)