[JQuery]JQuery ajax批量上传图片

在网上搜索了一下,发现以JQuery+ajax方式实现单张图片上传的代码是有的,但实现批量上传图片的程序却没搜索到,于是根据搜索到的代码,写了一个可以批量上传的。

         先看效果图

点击增加按钮,会增加一个选择框,如下图:

 

选择要上传的图片,效果图如下:

 

上传成功如下图:

 

 

 

下面来看代码:

前台html主要代码:

<button id="SubUpload" class="ManagerButton" onClick="TSubmitUploadImageFile();return false;">确定上传</button>&nbsp;&nbsp;

<button id="CancelUpload" class="ManagerButton" onClick="JavaScript:history.go(-1);">取消</button>&nbsp;&nbsp;

<button id="AddUpload" class="ManagerButton" onClick="TAddFileUpload();return false;">增加</button>

<tr><td class="tdClass">

         图片1

         </td><td class="tdClass">

         <input name="" size="60" id="uploadImg1" type="file" />

         <span id="uploadImgState1"></span>

         </td></tr>

 

 

 

 

 

 

 

 

 

 

因为用了JQuery,所以你完全可以把click事件放在js文件中

增加按钮js代码:

 

var TfileUploadNum=1; //记录图片选择框个数

var Tnum=1; //ajax上传图片时索引

         function TAddFileUpload()

         {

                   var idnum = TfileUploadNum+1;

                   var str="<tr><td class='tdClass'>图片"+idnum+"</td>";

                   str += "<td class='tdClass'><input name='' size='60' id='uploadImg"+idnum+"' type='file' /><span id='uploadImgState"+idnum+"'>";

                   str += "</span></td></tr>";

                   $("#imgTable").append(str);

                   TfileUploadNum += 1;

         }

 

 

 

 

 

 

 

 

 

 

确定上传按钮js代码:

 

function TSubmitUploadImageFile()

         {

                  M("SubUpload").disabled=true;

                   M("CancelUpload").disabled=true;

                   M("AddUpload").disabled=true;

                   setTimeout("TajaxFileUpload()",1000);//此为关键代码

}

 

 

 

 

 

 

 

 

关于setTimeout("TajaxFileUpload()",1000);这句代码:因为所谓的批量上传,其实还是一个一个的上传,给用户的只是一个假象。只所以要延时执行TajaxFileUpload(),是因为在把图片上传到服务器上时,我在后台给图片重新命名了,命名的规则是,如下代码:

 

 

Random rd = new Random();

StringBuilder serial = new StringBuilder();

serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));

serial.Append(rd.Next(0, 999999).ToString());

return serial.ToString();

 

 

 

 

 

即使我命名精确到毫秒,另外再加上随机数,可是还是有上传的第二张图片把上传的第一张图片覆盖的情况出现。所以此处我设置了延时1秒后在上传下一张图片。刚开始做这个东西的时候,用的是for循环,来把所有的图片一个一个的循环地用ajax上传,可是for循环速度太快了,可能第一张图片还没来得及ajax,第二张就被for过来了,还是有第二张覆盖第一张的情况出现。

下面来看TajaxFileUpload()函数,代码如下:

 

function TajaxFileUpload()

         {

                   if(Tnum<TfileUploadNum+1)

                   {

                            //准备提交处理

                            $("#uploadImgState"+Tnum).html("<img src=../images/loading.gif />");

                            //开始提交

                            $.ajax

                            ({

                                     type: "POST",

                                     url:"http://localhost/ajaxText2/Handler1.ashx",

                                     data:{upfile:$("#uploadImg"+Tnum).val(),category:$("#pcategory").val()},

                                     success:function (data, status)

                                     {

                                               //alert(data);

                                               var stringArray = data.split("|");

                                              

                                               if(stringArray[0]=="1")

                                               {

                                                        //stringArray[0]    成功状态(1为成功,0为失败)

                                                        //stringArray[1]    上传成功的文件名

                                                        //stringArray[2]    消息提示

                                                        $("#uploadImgState"+Tnum).html("<img src=../images/note_ok.gif />");//+stringArray[1]+"|"+stringArray[2]);

                                               }           

                                               else

                                               {

                                                        //上传出错

                                                        $("#uploadImgState"+Tnum).html("<img src=../images/note_error.gif />"+stringArray[2]);//+stringArray[2]+"");

                                               }

                                               Tnum++;

                                             setTimeout("TSubmitUploadImageFile()",0);

                                      }

                             });                     

                   }

         }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 上面的代码没什么可说的,很容易看懂。下面来看Handler1.ashx(一般处理程序)如何来处理post过来的图片的(此代码来自网上,具体地址忘记了),下面只给出关键代码,全部代码在附件里。

1

  

string _fileNamePath = "";

            try

            {

                _fileNamePath = context.Request.Form["upfile"];

                //开始上传

                string _savedFileResult = UpLoadFile(_fileNamePath);

                context.Response.Write(_savedFileResult);

            }

            catch

            {

                context.Response.Write("0|error|上传提交出错");

            }

 

 

 

 

 

 

 

 

 

 

 

 

2

 

//生成将要保存的随机文件名

string fileName = GetFileName() + fileNameExt;

//物理完整路径                   

string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);

//检查是否有该路径 没有就创建

if (!Directory.Exists(toFileFullPath))

{

     Directory.CreateDirectory(toFileFullPath);

}

///创建WebClient实例      

WebClient myWebClient = new WebClient();

//设定windows网络安全认证   方法1

myWebClient.Credentials = CredentialCache.DefaultCredentials;

//要上传的文件      

FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);

//FileStream fs = OpenFile();      

BinaryReader r = new BinaryReader(fs);

//使用UploadFile方法可以用下面的格式      

//myWebClient.UploadFile(toFile, "PUT",fileNamePath);      

byte[] postArray = r.ReadBytes((int)fs.Length);

Stream postStream = myWebClient.OpenWrite(toFile, "PUT");

if (postStream.CanWrite)

{

postStream.Write(postArray, 0, postArray.Length);

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3、检查是否合法的上传文件

 

private bool CheckFileExt(string _fileExt)

{

     string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg" };

     for (int i = 0; i < allowExt.Length; i++)

     {

         if (allowExt[i] == _fileExt) { return true; }

     }

    return false;

}

4、生成要保存的随即文件名

 

 

 

 

 

 

 

 

  

public static string GetFileName()

{

            Random rd = new Random();

            StringBuilder serial = new StringBuilder();

            serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));

            serial.Append(rd.Next(0, 999999).ToString());

            return serial.ToString();

}

 

 

 

 

 

 

 

Ok,基本上这个批量上传图片的jQuery+ajax方式实现的程序完成了。如果你要上传word文档,pdf文件,只要稍作修改,就可以实现了。

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏