SpringMVC进行文件上传实例
jsp 页面
注意:1、 method="post"
2、enctype="multipart/form-data"
3、<input name="file" id="password" type="file" />
4、当指定requestMapping单独为upload的时候,发现当URL中单独只有upload时它的method会被解析为GET,会报异常。
这就是解决方法
<form class="form-horizontal" action="fileupload" method="post" enctype="multipart/form-data"> <p style="color:red;"> ${null==requestScope.msg?"":requestScope.msg} </p> <fieldset> <div class="input-prepend" title="Password" data-rel="tooltip"> <span class="add-on"><i class="icon-lock"></i></span><input class="input-large span10" name="file" id="password" type="file" /> </div> <div class="clearfix"></div> <div class="input-prepend"> <label class="remember" for="remember"><input type="checkbox" id="remember" />记住用户</label> </div> <div class="clearfix"></div> <p class="center span5"> <button type="submit" class="btn btn-primary">提交</button> </p> </fieldset> </form>
2、SpringMVC配置文件中增加
<!-- 文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8" /> <property name="maxUploadSize" value="10485760000" /> <property name="maxInMemorySize" value="40960" /> </bean>
3、加jar包 commons-io-2.1.jar,commons-fileupload-1.2.2.jar
4、后台Action
@Controller public class FireUp { @RequestMapping(value = "fileupload") public String fileupload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) { String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename();System.out.println("文件上传"+path+"--"+fileName);File targetFile = new File(path, fileName); if(!targetFile.exists()){ targetFile.mkdirs(); } //保存 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName); return "result"; } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。