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提交的action名称,即把upload修改为其他名称,或者不单独为"项目名/upload"就不会有这个问题。当然,修改后要修改相应的requesetMapping。
这就是解决方法


<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"; } }





SpringMVC进行文件上传实例,布布扣,bubuko.com

SpringMVC进行文件上传实例

上一篇:阿里云服务器按量付费和包年包月付费模式区别及选择方法


下一篇:java反编译工具