SpringMVC 【ajax上传文件】
本文内容纲要:
页面代码:
<%@pagelanguage="java"pageEncoding="UTF-8"%>
<html>
<head>
<linktype="text/css"
href="<%=request.getContextPath()%>/css/ajaxfileupload.css"
rel="stylesheet"/>
<scripttype="text/javascript"
src="<%=request.getContextPath()%>/js/jquery-1.8.3.js"></script>
<scripttype="text/javascript"
src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script>
<scripttype="text/javascript">
//全局计数对象
vari=1;
//显示本地图片
functiononChangFile(seqId){
varobj=getObjectURL(document.getElementById('file_'+seqId).files[0]);
$('#img_'+seqId).attr('src',obj);
//文件改变,单上传功能启用
$('#uploadButton_'+seqId).attr("disabled",false);
};
//获取二进制对象
functiongetObjectURL(file){
varurl=null;
if(window.createObjectURL!=undefined){//basic
url=window.createObjectURL(file);
}elseif(window.URL!=undefined){//mozilla(firefox)
url=window.URL.createObjectURL(file);
}elseif(window.webkitURL!=undefined){//webkitorchrome
url=window.webkitURL.createObjectURL(file);
}
returnurl;
};
//添加一个单位
functionaddUpload(){
i++;
vars='<trid="tr_'+i+'">';
s+='<td><imgid="img_'+i+'"height="100"width="100"src=""></td>';
s+='<td><inputid="file_'+i+'"type="file"name="myfiles"onchange="onChangFile(\''+i+'\')"/></td>';
s+='<td><inputid="uploadButton_'+i+'"type="button"value="上传"disabledonclick="UploadFile(\''+i+'\')"/></td>';
s+='<td><buttononclick="deletUpload(\''+i+'\')"><fontcolor="red">X</font></button></td>';
//s+='<td><imgid="img_'+i+'_'+i+'"height="100"width="100"src=""></td>';
s+='<td><spanid="message_'+i+'"></span><spanid="url_'+i+'"></span></td>';
s+='</tr>';
$("#uploadtable>tbody").append(s);
$('#file_'+i).trigger("click");
};
//删除一个单位
functiondeletUpload(seqId){
$('#tr_'+seqId).remove();
};
//异步文件上传(jquery)
functionUploadFile(seqId){
$.ajaxFileUpload({
url:"<%=request.getContextPath()%>/fileUpload/fileFTPUpload.do",//submittoUploadFileServlet
secureuri:false,
fileElementId:'file_'+seqId,
dataType:'JSON',//orjsonxmlwhateveryoulike~
data:{//加入的文本参数
"formFieldId":"param1",
},
success:function(data,status){
data=data.substring(data.indexOf("{"),data.indexOf("}")+1);
varjson=eval("("+data+")");
//提示信息
$("#message_"+seqId).text(json.message);
//url回写
$("#url_"+seqId).text(json.fileUrl);
$("#uploadButton_"+seqId).attr("disabled",true);
},
error:function(data,status,e){
$("#result").append(data);
}
});
returnfalse;
}
//批量提交
functionbatchUpload(){
//所有可用按钮触发
$("input[id^='uploadButton']").each(function(){
if($(this).attr("disabled")==undefined){
//$(this).trigger("click");
$(this).trigger("click");
}
});
};
</script>
</head>
<body>
<tableid="uploadtable"style="margin:auto;">
<tbody>
<trid="tr_1">
<tdbgcolor="#aaaaaa">
<imgid="img_1"height="100"width="100"src="">
</td>
<td>
<inputid="file_1"type="file"name="myfiles"onchange="onChangFile('1')"/>
</td>
<td>
<inputid="uploadButton_1"type="button"value="上传"onclick="UploadFile('1')"/>
</td>
<td>
<buttononclick="deletUpload('1')">
<fontcolor="red">X</font>
</button>
</td>
<td>
<spanid="message_1"></span>
<spanid="url_1"></span>
</td>
</tr>
</tbody>
</table>
<tablestyle="margin:auto;">
<tr>
<td><inputtype="button"onclick="addUpload()"value="添加"/>
</td>
<td><inputtype="button"onclick="batchUpload()"value="批量上传"/></td>
<td><divid="result"style="margin-left:200px"></div></td>
</tr>
</table>
</body>
</html>
java代码:
@RequestMapping(value="/fileFTPUpload.do",method=RequestMethod.POST)
@ResponseBody
publicStringhandleFormUpload(
@RequestParam("myfiles")MultipartFilefileField,
@RequestParam(value="formFieldId",required=false,defaultValue="pic_url")StringformFieldId,
HttpServletRequestrequest,Modelmodel){
System.out.println(formFieldId);
StringcurDateDir=DateUtil.getCurrDateStr("yyyyMMdd");//当天日期,用于当天的目录名称
//图片地址
StringBufferpicUrl=newStringBuffer(request.getSession().getServletContext().getRealPath("/"));
//格式:/picture/日期/文件名
picUrl=picUrl.append("picture\\").append(curDateDir).append("\\");
//可行后缀
finalString[]allowedExt=newString[]{"gif","GIF",
"jpg","JPG","swf","SWF","PNG","png","FLV",
"flv","FLA","fla","jpeg"};
StringfileName="";
try{
//得到文件的扩展名(无扩展名时将得到全名)
Stringt_ext=fileField.getContentType().substring(
fileField.getContentType().lastIndexOf("/")+1);
System.out.println("文件后缀为:"+t_ext);
//判断后缀是否被允许
booleanallowFlag=false;
for(Stringstring:allowedExt){
if(string.equals(t_ext.toLowerCase())){
allowFlag=true;
break;
}
}
System.out.println("aa");
//后缀不符
if(allowFlag==false){
Stringmessage="请上传以下类型的文件:";
for(Stringstring:allowedExt){
message+="*."+string;
}
message+="\n当前上传的文件格式为:"+t_ext;
Map<String,String>map=newHashMap<String,String>();
map.put("formFieldId",formFieldId);
map.put("message",message);
returnJSONObject.valueToString(map);
}
//文件1000K大小限制
if(fileField.getSize()>1000*1024){
Map<String,String>map=newHashMap<String,String>();
map.put("formFieldId",formFieldId);
map.put("message","上传文件大小不被允许!");
returnJSONObject.valueToString(map);
}
System.out.println("cc");
//文件名
Stringname=fileField.getOriginalFilename();
//处理文件名
fileName=FileUtil.dealName(name);
//先上传到web
FileUtils.copyInputStreamToFile(fileField.getInputStream(),newFile(picUrl.toString(),fileName));
System.out.println(picUrl.toString()+fileName);
//生成图片地址
picUrl.append(fileName);
}
catch(Exceptione){
e.printStackTrace();
}
System.out.println("ff");
Map<String,String>map=newHashMap<String,String>();
map.put("formFieldId",formFieldId);
map.put("fileUrl",picUrl.toString());
map.put("message","上传成功!");
returnJSONObject.valueToString(map);
}
web.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!--DispatcherServlet是一个Servlet,所以可以配置多个DispatcherServlet-->
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/one-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup><!--启动顺序,让这个Servlet随Servlet容器一起启动-->
</servlet>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--加了SpringMVCFilter之后,也只能处理post的数据乱码-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--默认首页-->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
one-serlvet.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!--自动扫描的包名(组件装配)-->
<context:component-scanbase-package="com.action"/>
<!--【视图解析器】,根据【Controller】返回的字符串【映射】到相应的【jsp】-->
<beanid="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="prefix"value="/WEB-INF/jsp/"/>
<propertyname="suffix"value=".jsp"/>
</bean>
<!--SpringMVC上传文件时,需要配置MultipartResolver处理器-->
<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和-->
<propertyname="maxUploadSize"value="100000000"/>
<!--SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException-->
<!--该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中-->
</bean>
<beanid="exceptionResolver"class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<propertyname="exceptionMappings">
<props>
<!--遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面-->
<propkey="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
</props>
</property>
</bean>
<beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<propertyname="messageConverters">
<list>
<refbean="stringHttpMessageConverter"/>
</list>
</property>
</bean>
<beanid="stringHttpMessageConverter"class="org.springframework.http.converter.StringHttpMessageConverter">
<propertyname="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<!--【加载】其他SpringMVC【子容器】-->
</beans>
本文内容总结:
原文链接:https://www.cnblogs.com/luffya/p/3673725.html