ajaxfileupload的使用实例

前端之家收集整理的这篇文章主要介绍了ajaxfileupload的使用实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_301_0@ http://blog.csdn.net/sidongxue2/article/details/43952191

今天简单总结一下ajaxfileupload的用法,具体实例如下:

1.上传一个文件并携带多个参数.
2.上传多个文件并携带多个参数.
扩展:可以通过jquery扩展为添加文件选择框,去除文件选择框,而不是写死只能上传几个文件.
3.上传一个文件并携带多个参数,同时上传完成之后,及时显示.
4.上传一个文件并携带多个参数,上传之前实现预览.

5.上传一个文件,并携带多个参数.

通过css将界面完善的更加人性化:点击图片选择文件.

项目通过maven构建,前后台通过springmvc交互数据,spring采用注解方式.

a.闲话少说先看web.xml文件,如下:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <web-appversion="2.5"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  7. display-name>message-web</>
  8. <!--配置log4j配置文件和监听器-->
  9. context-paramparam-name>log4jConfigLocationparam-value>classpath:log4j.propertieslistenerlistener-class>org.springframework.web.util.Log4jConfigListener
  10. <!--配置springmvc主控servlet-->
  11. servletservlet-name>springmvcservlet-class>org.springframework.web.servlet.DispatcherServletinit-param>contextConfigLocation>classpath:springmvc.xmlservlet-mappingurl-pattern>*.mvc<!--添加字符集过滤器-->
  12. filterfilter-name>encodingFilterfilter-class>org.springframework.web.filter.CharacterEncodingFilter>encoding>UTF-8filter-mapping>/*web-app>
b.接着看spring配置文件和log4j配置文件,

    beansxmlns="http://www.springframework.org/schema/beans"
  1. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"
  2. xmlns:context="http://www.springframework.org/schema/context"
  3. xsi:schemaLocation="http://www.springframework.org/schema/beans
  4. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  5. http://www.springframework.org/schema/context
  6. http://www.springframework.org/schema/context/spring-context-4.0.xsd"<!--配置controller扫描-->
  7. context:component-scanbase-package="com.ilucky.ajaxfileupload"/>
  8. <!--设置上传文件的最大尺寸为100MB-->
  9. beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"propertyname="maxUploadSize"value>102400000propertybeanbeans>
    #Loggers
  1. log4j.rootLogger=debug,console,file
  2. #console
  3. log4j.appender.console=org.apache.log4j.ConsoleAppender
  4. log4j.appender.console.Threshold=DEBUG
  5. log4j.appender.console.layout=org.apache.log4j.PatternLayout
  6. log4j.appender.console.layout.ConversionPattern=[%d]-%p-%l-%m%n
  7. #file
  8. log4j.appender.file=org.apache.log4j.RollingFileAppender
  9. log4j.appender.file.Append=true
  10. log4j.appender.file.Threshold=DEBUG
  11. log4j.appender.file.ImmediateFlush=true
  12. log4j.appender.file.File=../webapps/ajaxfileupload.log
  13. log4j.appender.file.MaxFileSize=2500KB
  14. log4j.appender.file.MaxBackupIndex=20
  15. log4j.appender.file.layout=org.apache.log4j.PatternLayout
  16. log4j.appender.file.layout.ConversionPattern=[%d]-%p-%l-%m%n
c.然后看控制类.

[java]
    packagecom.ilucky.ajaxfileupload;
  1. importjava.io.File;
  2. importjava.io.PrintWriter;
  3. importjava.util.HashMap;
  4. importjava.util.Map;
  5. importjavax.servlet.http.HttpServletRequest;
  6. importjavax.servlet.http.HttpServletResponse;
  7. importorg.apache.log4j.Logger;
  8. importorg.springframework.context.annotation.Scope;
  9. importorg.springframework.stereotype.Controller;
  10. importorg.springframework.web.bind.annotation.RequestMapping;
  11. importorg.springframework.web.bind.annotation.RequestParam;
  12. importorg.springframework.web.multipart.MultipartFile;
  13. importcom.alibaba.fastjson.JSON;
  14. /**
  15. *注意:
  16. *1.如果从前台传到后台的数据出现中文乱码,在web.xml文件中配置字符集过滤器.
  17. *2.如果从后台传到前台的数据出现中文乱码,为response设置编码方式.
  18. *@authorIluckySi
  19. *@since20150213
  20. */
  21. @Controller("uploadFileController")
  22. @Scope("prototype")
  23. @RequestMapping("/uploadFileController")
  24. publicclassUploadFileController{
  25. privatestaticLoggerlogger=Logger.getLogger(UploadFileController.class);
  26. @RequestMapping("/ajaxfileupload")
  27. voidajaxfileupload(HttpServletRequestrequest,HttpServletResponseresponse,
  28. @RequestParam(value="username",required=true)Stringusername,
  29. @RequestParam(value="password",153); font-weight:bold; background-color:inherit">true)Stringpassword,100); background-color:inherit">@RequestParam(value="photo",153); font-weight:bold; background-color:inherit">true)MultipartFilephoto){
  30. logger.info("后台收到参数:username="+username+",password="+password+
  31. ",photo="+photo.getOriginalFilename());
  32. response.setCharacterEncoding("utf-8");
  33. PrintWriterpw=null;
  34. Map<String,String>result=newHashMap<String,String>();
  35. StringimagePath=request.getSession().getServletContext().getRealPath("/");
  36. StringimageName="image/"+photo.getOriginalFilename().replace("","");
  37. try{
  38. *模拟位置1:前台error方法.
  39. *模拟代码:intj=2/0;
  40. */
  41. pw=response.getWriter();
  42. /**
  43. *模拟位置2:前台success方法.
  44. *模拟代码:intj=2/0;
  45. if(photo.getSize()>0){
  46. photo.transferTo(newFile(imagePath+imageName));
  47. logger.info("存储图片成功:"+photo.getOriginalFilename());
  48. }
  49. result.put("result","success");
  50. result.put("message","存储图片成功!");
  51. }catch(Exceptione){
  52. logger.error("存储图片失败:"+e);
  53. "failure");
  54. "存储图片失败!");
  55. finally{
  56. pw.print(JSON.toJSONString(result));
  57. }
  58. @RequestMapping("/ajaxfileupload2")
  59. voidajaxfileupload2(HttpServletRequestrequest,153); font-weight:bold; background-color:inherit">true)MultipartFile[]photo){
  60. +photo.length);
  61. try{
  62. pw=response.getWriter();
  63. for(inti=0;i<photo.length;i++){
  64. MultipartFilep=photo[i];
  65. if(p.getSize()>0){
  66. StringimageName="image/"+p.getOriginalFilename().replace("","");
  67. p.transferTo( logger.info("存储图片成功:"+p.getOriginalFilename());
  68. result.put("result","success");
  69. result.put("message","存储图片成功!");
  70. }catch(Exceptione){
  71. logger.error("存储图片失败:"+e);
  72. "failure");
  73. "存储图片失败!");
  74. finally{
  75. pw.print(JSON.toJSONString(result));
  76. @RequestMapping("/ajaxfileupload3")
  77. voidajaxfileupload3(HttpServletRequestrequest,153); font-weight:bold; background-color:inherit">true)MultipartFilephoto){
  78. logger.info("后台收到参数:username="+username+",password="+password+
  79. ",photo="+photo.getOriginalFilename());
  80. response.setCharacterEncoding("utf-8");
  81. PrintWriterpw=null;
  82. Map<String,String>();
  83. StringimagePath=request.getSession().getServletContext().getRealPath("/");
  84. StringimageName="image/"+photo.getOriginalFilename().replace("",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> photo.transferTo(newFile(imagePath+imageName));
  85. logger.info("存储图片成功:"+photo.getOriginalFilename());
  86. @RequestMapping("/ajaxfileupload4")
  87. voidajaxfileupload4(HttpServletRequestrequest,100); background-color:inherit">@RequestMapping("/ajaxfileupload5")
  88. voidajaxfileupload5(HttpServletRequestrequest,248); margin:0px!important; padding:0px 3px 0px 10px!important"> }
d.依次看5个实例.

    <!--
  1. 上传一个文件并携带多个参数.
  2. @authorIluckySi
  3. @since20150213
  4. --<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%<%
  5. Stringpath=request.getContextPath();
  6. StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  7. % <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"htmlheadbasehref="<%=basePath%>"title>testMetahttp-equiv="pragma"content="no-cache"Metahttp-equiv="cache-control"content="no-cache"Metahttp-equiv="expires"content="0"Metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"Metahttp-equiv="description"content="Thisismypage"Metahttp-equiv="X-UA-Compatible"content="IE=edge"Metaname="viewport"content="width=device-width,initial-scale=1"scriptsrc="${pageContext.request.contextPath}/js/jquery-1.11/jquery.min.js">scriptscriptsrc="${pageContext.request.contextPath}/js/ajaxfileupload/ajaxfileupload.js" varuploadUrl='${pageContext.request.contextPath}/uploadFileController/ajaxfileupload.mvc';
  8. $(function(){
  9. $('#upload').click(function(e){
  10. varusername=$('#username').val();
  11. varpassword=$('#password').val();
  12. varisValidate=false;
  13. if(username==''||password==''){
  14. $('#prompt').html('spanstyle="color:red">用户名和密码是必填项!span>');
  15. }else{
  16. isValidate=true;
  17. if(isValidate){
  18. $.ajaxFileUpload({
  19. url:uploadUrl,
  20. secureuri:false,
  21. //文件选择框的id属性.
  22. fileElementId:'photo',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> dataType:'json',248); margin:0px!important; padding:0px 3px 0px 10px!important"> data:{
  23. username:username,248); margin:0px!important; padding:0px 3px 0px 10px!important"> password:password
  24. },248); margin:0px!important; padding:0px 3px 0px 10px!important"> //注意:这里的success方法代表的是前台成功接收了后台返回的数据.
  25. success:function(data,status){
  26. if(data.result=='success'){
  27. alert(data.message);
  28. //继续成功的逻辑...
  29. }else{
  30. alert(data.message);
  31. //继续失败的逻辑...
  32. //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.
  33. //换句话说如果后台的异常没有捕获到,则认为是error.
  34. error:function(s,xml,status,e){
  35. console.info('上传图片失败:未知异常!');
  36. });
  37. });
  38. bodyformid="form"method="post"enctype="multipart/form-data"inputid="username"name="username"type="text"value="请输入姓名"/>
  39. inputid="password"name="password"type="password"value="请输入密码"inputid="photo"name="photo"type="file"imgid="img"src=""inputid="upload"type="button"value="上传"formdivid="prompt"div
      上传多个文件并携带多个参数.
    1. 扩展:可以通过jquery扩展为添加文件选择框,而不是写死只能上传几个文件.
    2. @authorIluckySi
    3. @since20150213
    4. --<%
    5. Stringpath=request.getContextPath();
    6. StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    7. % <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN" varuploadUrl='${pageContext.request.contextPath}/uploadFileController/ajaxfileupload2.mvc';
    8. $(function(){
    9. $('#upload').click(function(e){
    10. varusername=$('#username').val();
    11. varpassword=$('#password').val();
    12. varisValidate=false;
    13. if(username==''||password==''){
    14. $('#prompt').html('>');
    15. isValidate=true;
    16. if(isValidate){
    17. $.ajaxFileUpload({
    18. url:uploadUrl,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> secureuri:false,248); margin:0px!important; padding:0px 3px 0px 10px!important"> //文件选择框的id属性.
    19. fileElementId:['photo1','photo2','photo3'],248); margin:0px!important; padding:0px 3px 0px 10px!important"> dataType:'json',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> data:{
    20. username:username,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> password:password
    21. },108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> //注意:这里的success方法代表的是前台成功接收了后台返回的数据.
    22. success:function(data,status){
    23. if(data.result=='success'){
    24. //继续成功的逻辑...
    25. //继续失败的逻辑...
    26. //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.
    27. //换句话说如果后台的异常没有捕获到,则认为是error.
    28. error:function(s,e){
    29. console.info('上传图片失败:未知异常!');
    30. inputid="photo1"name="photo"type="file"inputid="photo2"name="photo"type="file"inputid="photo3"name="photo"type="file"
        上传一个文件并携带多个参数,及时显示.
      1. varuploadUrl='${pageContext.request.contextPath}/uploadFileController/ajaxfileupload3.mvc';
      2. //及时预览.
      3. $('#img').attr('src',data.message).
      4. attr('width','100px').
      5. attr('height','100px');
        1. 上传之前实现预览.
        2. 难点:
        3. 对于Chrome,Firefox和IE10使用FileReader来实现.
        4. 对于IE6~9使用滤镜filter:progid:DXImageTransform.Microsoft.AlphaImageLoader来实现.
        5. varuploadUrl='${pageContext.request.contextPath}/uploadFileController/ajaxfileupload4.mvc';
        6. fileElementId:'photo',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> //重点:图片预览.
        7. functionpreview(file){
        8. varpreview=document.getElementById('preview');
        9. if(file.files&&file.files[0]){
        10. varreader=newFileReader();
        11. reader.onload=function(event){
        12. preview.innerHTML='<imgsrc="'+event.target.result+'"width="100px"height="100px"/>';
        13. };
        14. reader.readAsDataURL(file.files[0]);
        15. //没有用IE6~9进行测试.
        16. preview.innerHTML='divclass="img"style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\''+file.value+'\'">';
        17. inputid="photo"name="photo"type="file"onchange="preview(this)"divid="preview"
            上传一个文件,并携带多个参数.
          1. p>通过css将界面完善的更加人性化:点击图片选择文件.
          2. @since20150226
          3. styletype="text/css" .fileDiv{
          4. width:100px;
          5. height:40px;
          6. background:url(image/test.png);
          7. overflow:hidden;
          8. position:relative;
          9. .photo{
          10. position:absolute;
          11. top:-100px;
          12. .upFileButton{
          13. width:100px;
          14. height:40px;
          15. opacity:0;
          16. filter:alpha(opacity=0);
          17. cursor:pointer;
          18. style varuploadUrl='${pageContext.request.contextPath}/uploadFileController/ajaxfileupload5.mvc';
          19. divid="fileDiv"class="fileDiv"inputtype="file"id="photo"name="photo"class="photo"onchange="document.getElementById('photoName').innerHTML=this.value"inputtype="button"class="upFileButton"onclick="document.getElementById('photo').click()"divid="photoName">图片文件名称inputid="upload"class="upload"type="button"value="上传"e.最重要的是看ajaxfileupload.js文件,此文件进行了扩展,都是从网上找到的.

            [javascript]
            @H_502_2717@//JavaScriptDocument
          20. jQuery.extend({
          21. createUploadIframe:function(id,uri){
          22. //createframe
          23. varframeId='jUploadFrame'+id;
          24. variframeHtml='<iframeid="'+frameId+'"name="'+frameId+'"style="position:absolute;top:-9999px;left:-9999px"';
          25. if(window.ActiveXObject){
          26. if(typeofuri=='boolean'){
          27. iframeHtml+='src="'+'javascript:false'+'"';
          28. elsetypeofuri=='string'){
          29. iframeHtml+='src="'+uri+'"';
          30. iframeHtml+='/>';
          31. jQuery(iframeHtml).appendTo(document.body);
          32. returnjQuery('#'+frameId).get(0);
          33. createUploadForm://createform
          34. varformId='jUploadForm'+id;
          35. varfileId='jUploadFile'+id;
          36. varform=jQuery('<formaction=""method="POST"name="'+formId+'"id="'+formId+'"enctype="multipart/form-data"></form>');
          37. //使ajaxfileupload支持增加附加参数.
          38. if(data){
          39. variindata){
          40. jQuery('<inputtype="hidden"name="'+i+'"value="'+data[i]+'"/>').appendTo(form);
          41. //ajaxFileupload默认是只能上传一个文件,替换如下代码地实现多个文件上传.
          42. typeof(fileElementId)=='string'){
          43. fileElementId=[fileElementId];
          44. infileElementId){
          45. varoldElement=jQuery('#'+fileElementId[i]);
          46. varnewElement=jQuery(oldElement).clone();
          47. jQuery(oldElement).attr('id',fileId);
          48. jQuery(oldElement).before(newElement);
          49. jQuery(oldElement).appendTo(form);
          50. /*varoldElement=jQuery('#'+fileElementId);
          51. varnewElement=jQuery(oldElement).clone();
          52. jQuery(oldElement).attr('id',fileId);
          53. jQuery(oldElement).before(newElement);
          54. jQuery(oldElement).appendTo(form);*/
          55. //setattributes
          56. jQuery(form).css('position','absolute');
          57. jQuery(form).css('top','-1200px');
          58. jQuery(form).css('left','-1200px');
          59. jQuery(form).appendTo('body');
          60. returnform;
          61. ajaxFileUpload:function(s){
          62. //TODOintroduceglobalsettings,allowingtheclienttomodifythemforallrequests,notonlytimeout
          63. s=jQuery.extend({},jQuery.ajaxSettings,s);
          64. varid=newDate().getTime();
          65. varform=jQuery.createUploadForm(id,s.fileElementId,(typeof(s.data)=='undefined'?false:s.data));
          66. vario=jQuery.createUploadIframe(id,s.secureuri);
          67. varformId='jUploadForm'+id;
          68. //Watchforanewsetofrequests
          69. if(s.global&&!jQuery.active++){
          70. jQuery.event.trigger("ajaxStart");
          71. varrequestDone=false;
          72. //Createtherequestobject
          73. varxml={};
          74. if(s.global)
          75. jQuery.event.trigger("ajaxSend",[xml,s]);
          76. //Waitforaresponsetocomeback
          77. varuploadCallback=function(isTimeout){
          78. vario=document.getElementById(frameId);
          79. if(io.contentWindow){
          80. xml.responseText=io.contentWindow.document.body?io.contentWindow.document.body.innerHTML: xml.responseXML=io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
          81. if(io.contentDocument){
          82. xml.responseText=io.contentDocument.document.body?io.contentDocument.document.body.innerHTML: xml.responseXML=io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
          83. catch(e){
          84. jQuery.handleError(s,null,e);
          85. if(xml||isTimeout=="timeout"){
          86. requestDone=true;
          87. varstatus;
          88. status=isTimeout!="timeout"?"success":"error";
          89. //Makesurethattherequestwassuccessfulornotmodified
          90. if(status!="error"){
          91. //processthedata(runsthexmlthroughhttpDataregardlessofcallback)
          92. vardata=jQuery.uploadHttpData(xml,s.dataType);
          93. //Ifalocalcallbackwasspecified,fireitandpassitthedata
          94. if(s.success)
          95. s.success(data,status);
          96. //Firetheglobalcallback
          97. jQuery.event.trigger("ajaxSuccess",153); font-weight:bold; background-color:inherit">else
          98. status="error";
          99. jQuery.handleError(s,e);
          100. //Therequestwascompleted
          101. if(s.global)
          102. jQuery.event.trigger("ajaxComplete",s]);
          103. //HandletheglobalAJAXcounter
          104. if(s.global&&!--jQuery.active)
          105. jQuery.event.trigger("ajaxStop");
          106. //Processresult
          107. if(s.complete)
          108. s.complete(xml,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> jQuery(io).unbind();
          109. setTimeout(function(){
          110. jQuery(io).remove();
          111. jQuery(form).remove();
          112. catch(e){
          113. xml= };
          114. //Timeoutchecker
          115. if(s.timeout>0){
          116. //Checktoseeiftherequestisstillhappening
          117. if(!requestDone)uploadCallback("timeout");
          118. varform=jQuery('#'+formId);
          119. jQuery(form).attr('action',s.url);
          120. jQuery(form).attr('method','POST');
          121. jQuery(form).attr('target',frameId);
          122. if(form.encoding){
          123. jQuery(form).attr('encoding','multipart/form-data');
          124. else{
          125. jQuery(form).attr('enctype','multipart/form-data');
          126. jQuery(form).submit();
          127. jQuery('#'+frameId).load(uploadCallback);
          128. return{abort:function(){}};
          129. uploadHttpData:function(r,type){
          130. vardata=!type;
          131. data=type=="xml"||data?r.responseXML:r.responseText;
          132. //Ifthetypeis"script",evalitinglobalcontext
          133. if(type=="script")
          134. jQuery.globalEval(data);
          135. //GettheJavaScriptobject,ifJSONisused.
          136. if(type=="json")
          137. //针对ajaxfileupload返回json带<pre>标签解,
          138. //决方案为将eval("data="+data);换成data=jQuery.parseJSON(jQuery(data).text());
          139. //eval("data="+data);
          140. data=jQuery.parseJSON(jQuery(data).text());
          141. //evaluatescriptswithinhtml
          142. if(type=="html")
          143. jQuery("<div>").html(data).evalScripts();
          144. returndata;
          145. //针对ajaxfileupload.js结合低版本jquery报异常:TypeError:jQuery.handleErrorisnotafunction,添加如下代码.
          146. handleError:function(s,xhr,e){
          147. if(s.error){
          148. s.error.call(s.context||s,e);
          149. if(s.global){
          150. (s.context?jQuery(s.context):jQuery.event).trigger("ajaxError",[xhr,s,e]);
          151. });
          大功告成,亲以后有什么简答的上传工作,就交给他吧!!! 原文链接:https://www.f2er.com/ajax/163646.html

          猜你在找的Ajax相关文章