ajaxfileupload的使用实例以及上传报错

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

报错先检查PHP.ini 的大小限制

PHP.ini修改PHP上传文件大小限制的方法详解

打开PHP.ini,首先找到
file_uploads = on ;是否允许通过HTTP上传文件的开关。默认为ON即是开
upload_tmp_dir ;文件上传至服务器上存储临时文件的地方,如果没指定就会用系统默认的临时文件
upload_max_filesize = 8m ;望文生意,即允许上传文件大小的最大值。默认为2M
post_max_size = 8m ;指通过表单POST给PHP的所能接收的最大值,包括表单里的所有值。默认为8M
一般地,设置好上述四个参数后,上传<=8M的文件是不成问题,在网络正常的情况下。
但如果要上传>8M的大体积文件,只设置上述四项还一定能行的通。

进一步配置以下的参数
max_execution_time = 600 ;每个PHP页面运行的最大时间值(秒),默认30秒
max_input_time = 600 ;每个PHP页面接收数据所需的最大时间,默认60秒
memory_limit = 8m ;每个PHP页面所吃掉的最大内存,默认8M
把上述参数修改后,在网络所允许的正常情况下,就可以上传大体积文件
max_execution_time = 600
max_input_time = 600
memory_limit = 32m
file_uploads = on
upload_tmp_dir = /tmp
upload_max_filesize = 32m
post_max_size = 32m

今天简单总结一下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配置文件, c.然后看控制类.
    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)"> }
d.依次看5个实例.
copy
<!--
  • 上传一个文件并携带多个参数.
  • @authorIluckySi
  • @since20150213
  • --<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%<%
  • Stringpath=request.getContextPath();
  • StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  • % <!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';
  • $(function(){
  • $('#upload').click(function(e){
  • varusername=$('#username').val();
  • varpassword=$('#password').val();
  • varisValidate=false;
  • if(username==''||password==''){
  • $('#prompt').html('spanstyle="color:red">用户名和密码是必填项!span>');
  • }else{
  • isValidate=true;
  • if(isValidate){
  • $.ajaxFileUpload({
  • url:uploadUrl,
  • secureuri:false,
  • //文件选择框的id属性.
  • 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)"> data:{
  • username:username,248)"> password:password
  • },248)"> //注意:这里的success方法代表的是前台成功接收了后台返回的数据.
  • success:function(data,status){
  • if(data.result=='success'){
  • alert(data.message);
  • //继续成功的逻辑...
  • }else{
  • alert(data.message);
  • //继续失败的逻辑...
  • //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.
  • //换句话说如果后台的异常没有捕获到,则认为是error.
  • error:function(s,xml,status,e){
  • console.info('上传图片失败:未知异常!');
  • });
  • });
  • bodyformid="form"method="post"enctype="multipart/form-data"inputid="username"name="username"type="text"value="请输入姓名"/>
  • inputid="password"name="password"type="password"value="请输入密码"inputid="photo"name="photo"type="file"imgid="img"src=""inputid="upload"type="button"value="上传"formdivid="prompt"divcopy
    上传多个文件并携带多个参数.
  • 扩展:可以通过jquery扩展为添加文件选择框,而不是写死只能上传几个文件.
  • @authorIluckySi
  • @since20150213
  • --<%
  • Stringpath=request.getContextPath();
  • StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  • % <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN" varuploadUrl='${pageContext.request.contextPath}/uploadFileController/ajaxfileupload2.mvc';
  • $(function(){
  • $('#upload').click(function(e){
  • varusername=$('#username').val();
  • varpassword=$('#password').val();
  • varisValidate=false;
  • if(username==''||password==''){
  • $('#prompt').html('>');
  • isValidate=true;
  • if(isValidate){
  • $.ajaxFileUpload({
  • 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)"> //文件选择框的id属性.
  • fileElementId:['photo1','photo2','photo3'],248)"> dataType:'json',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> data:{
  • 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
  • },108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> //注意:这里的success方法代表的是前台成功接收了后台返回的数据.
  • success:function(data,status){
  • if(data.result=='success'){
  • //继续成功的逻辑...
  • //继续失败的逻辑...
  • //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.
  • //换句话说如果后台的异常没有捕获到,则认为是error.
  • error:function(s,e){
  • console.info('上传图片失败:未知异常!');
  • inputid="photo1"name="photo"type="file"inputid="photo2"name="photo"type="file"inputid="photo3"name="photo"type="file"copy
    上传一个文件并携带多个参数,及时显示.
  • varuploadUrl='${pageContext.request.contextPath}/uploadFileController/ajaxfileupload3.mvc';
  • //及时预览.
  • $('#img').attr('src',data.message).
  • attr('width','100px').
  • attr('height','100px');
  • copy
    难点:
  • 对于Chrome,Firefox和IE10使用FileReader来实现.
  • 对于IE6~9使用滤镜filter:progid:DXImageTransform.Microsoft.AlphaImageLoader来实现.
  • varuploadUrl='${pageContext.request.contextPath}/uploadFileController/ajaxfileupload4.mvc';
  • fileElementId:'photo',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> //重点:图片预览.
  • functionpreview(file){
  • varpreview=document.getElementById('preview');
  • if(file.files&&file.files[0]){
  • varreader=newFileReader();
  • reader.onload=function(event){
  • preview.innerHTML='<imgsrc="'+event.target.result+'"width="100px"height="100px"/>';
  • };
  • reader.readAsDataURL(file.files[0]);
  • //没有用IE6~9进行测试.
  • preview.innerHTML='divclass="img"style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\''+file.value+'\'">';
  • inputid="photo"name="photo"type="file"onchange="preview(this)"divid="preview"copy
    上传一个文件,并携带多个参数.
  • p>通过css将界面完善的更加人性化:点击图片选择文件.
  • @since20150226
  • styletype="text/css" .fileDiv{
  • width:100px;
  • height:40px;
  • background:url(image/test.png);
  • overflow:hidden;
  • position:relative;
  • .photo{
  • position:absolute;
  • top:-100px;
  • .upFileButton{
  • width:100px;
  • height:40px;
  • opacity:0;
  • filter:alpha(opacity=0);
  • cursor:pointer;
  • style varuploadUrl='${pageContext.request.contextPath}/uploadFileController/ajaxfileupload5.mvc';
  • 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文件,此文件进行了扩展,都是从网上找到的.
      //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/161815.html

    猜你在找的Ajax相关文章