---
title: "用jQuery和Spring做ajax文件上传应该注意的一个问题！"
author: "EwinLive"
date: "2010-12-18T15:16:26Z"
tags: ["Ajax", "MVC", "Spring", "jQuery", "json"]
categories: ["编程语言"]
slug: "jquery-spring-ajax"
draft: false
lastmod: "2010-12-18T15:19:06Z"
id: 846251
url: "https://ewinlive.iteye.com/blog/846251"
---

我自从用了jQuery之后，操作html基本就靠$('#XXX')了。但是这几天重构代码，发现一个文件上传功能却莫名其妙的出错了。

我后台用的是Spring（IOC+MVC）+Hibernate，前端用jQuery+ajaxfileupload插件。这个程序原来是好好的，可不知被我改了哪，居然不响应了。

重新回顾一下全过程：

1.html表单

```
<div id="add_document_form">
	<ul>
		<li>
			<p>分类：</p>
			<select id="document_category" required="true">
				<option value="diya">抵押贷款</option>
				<option value="zhiya">质押贷款</option>
				<option value="xinyong">信用贷款</option>
				<option value="danbao">担保贷款</option>
			</select>
		</li>
		<li>
			<p>文件：</p>
			<input id="select_document"  type="file" required="true" />
		</li>
	</ul>
</div>	
```

 2.配置Spring MVC

 

```
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"
	default-lazy-init="false" default-autowire="byName">
	
	<!-- ①：对web包中的所有类进行扫描，以完成Bean创建和自动依赖注入的功能 -->
	<context:component-scan base-package="org.dreamworker.**.controller" />
	
	<!-- ②：启动Spring MVC的注解功能，完成请求和注解POJO的映射 -->
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

	<!-- 文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="100000000" />
		<property name="defaultEncoding" value="UTF-8" />
	</bean>
</beans>
```

 3.创建Controller，我已经把请求转发到Servic了。（简化版）

 

```
/**
 * 上传文件
 * @param inputId input控件的id
 * @param request
 * @return
 */
public void doUpLoadFile(String inputId, HttpServletRequest request){
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		String fileDir =  "e:\\dreamworker\\crm\\" + user.getName() + "\\";//文件存放目录
		FileTools.addFolder(fileDir);
		
		CommonsMultipartFile cFile = (CommonsMultipartFile) multipartRequest.getFile(inputId);//获取上传文件
		if(null != cFile){
			if(!cFile.isEmpty()){
				//上传文件
				String uuid = new Long(UUID.randomUUID().getMostSignificantBits()).toString();
				File uploadedFile = new File(fileDir + uuid);
				FileCopyUtils.copy(cFile.getBytes(), uploadedFile);
			}
		}
}
```

 

应该都配好了吧，现在可以上传了：

```
$.ajaxFileUpload({
	url:'/crm/document.do?method=upLoadDocument&inputId='+inputId,
	secureuri:false,
	fileElementId:'select_document',
	dataType: 'JSON',
	success: function (json, status)
	{
		if(json.indexOf('<pre>') != -1) {
	          json = json.substring(5, json.length-6);
	    }         
	    eval("json=" + json); 
	    
	    if('ok' == json.state){
		    alert('上传成功，你可以在['+json.categoryRemark+']菜单中查看更新！');
	    }else{
	    	alert(json.msg);
	    }
	}
});
```

 

可结果却是莫名其妙，debug发现没有获取到上传的文件。崩溃，回顾整个流程，应该没问题啊！难道是Spring升级后API变了？在查阅文档后，我确定，问题还在上面代码上。继续无奈！！！

 

终于在逐行核对代码后，我找到了问题的终结。原来是html表单里面input标签没有设置"name"属性值的原因。

我原先写的是：

```
<input id="select_document" type="file" required="true" />
```

 其实应该写成：

 

```
<input id="select_document" name="select_document" type="file" required="true" />
```

 

我估计是ajaxfileupload插件的问题，一个小小的疏忽，竟然让我纠缠了5、6个钟头，引以为戒啊！