前台使用的是jquery的jquery.uploadify-v2.1.0插件,使用ajax。使用代码如下:
XML/HTML代码 jQuery("#uploadify").uploadify({ 'script' : '../imageUpload/upload/' + $("#sortId").val() + '.json',
这句话就是将请求发送到对应的uploadcontroller中,sortId是表示文件所属分类。
看下SpringMVC的使用方法:
在配置文件中添加如下配置:该文件即是SpringMVC对应的DispatcherServlet配置文件
XML/HTML代码 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> </bean>
一开始使用如下的方法上传:
Java代码 @RequestMapping(method = RequestMethod.POST, params = "action=upload") public String upload(ModelMap model, MultipartFile uploadify,BindingResult result) { }
结果报错了:
org.springframework.beans.BeanInstantiationException: Could not instantiate bean class
[org.springframework.web.multipart.MultipartFile]: Specified class is an interface
无法实例化,不知道是什么原因,对Spring不太熟悉,只能尝试用其他方式来实现了。
后来改成下面这种实现了:
Java代码 @RequestMapping(value = "/upload" + SORTID_BINDER_PATH, method = RequestMethod.POST) public void upload(HttpServletRequest request, HttpServletResponse response, @PathVariable java.lang.Integer sortId) { CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); commonsMultipartResolver.setDefaultEncoding("utf-8"); if (commonsMultipartResolver.isMultipart(request)) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = multipartRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multipartRequest.getFile((String) iter.next()); if (file != null) { String fileName = ""; fileName = sdf.format(new Date()) + "_" + file.getOriginalFilename(); String path = filePath + fileName; uploadPath += fileName; //重点就是这两句 File localFile = new File(path); file.transferTo(localFile); } } }
希望大家有好的方法提出来,一起学习。