ajaxfileupload的使用实例

前端之家收集整理的这篇文章主要介绍了ajaxfileupload的使用实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

            猜你在找的Ajax相关文章