Jquery插件AjaxUpload实现文件上传功能(模拟图片上传)

转载自:http://www.leapsoul.cn/?p=304

修改版

AjaxUpload

  Jquery插件AjaxUpload实现文件上传功能时无需创建form表单,即可实现Ajax方式的文件上传,当然根据需要也可以创建form表单。

准备工作

1、下载Jquery开发包和文件上传插件AjaxUpload

2、创建uploadfile.html,并引入Jquery开发包和AjaxUpload插件

1 <script src="js/jquery-1.3.js"></script>
2 <script src="js/ajaxupload.3.5.js"></script>

3、根据Jquery插件AjaxUpload的需要,创建一个触发Ajax文件上传功能的DIV

1 <ul> 
2     <li id="example"> 
3     <div id="upload_button">文件上传</div>
4     <p>已上传的文件列表:</p> 
5     <ol class="files"></ol>
6 </ul>

 

注释:由下面的代码我们可以看到Jquery插件AjaxUpload是根据upload_button这个DIV触发文件上传功能。

前台JS代码

  在代码中我设置了开关,根据需要可以匹配上传文件类型,同时也可以设置是以Ajax方式实现单个文件上传还是多个文件上传。

 1 $(document).ready(function () {
 2     var button = $('#upload_button'), interval;
 3     var fileType = "all", fileNum = "one";
 4     new AjaxUpload(button, {
 5         action: 'do/uploadfile.php',
 6         /*
 7         type: "POST", //提交方式
 8         data:{//还可以提交的值
 9             'buttoninfo':button.text()
10         },
11         autoSubmit:false,//选择文件后,是否自动提交
12         */
13         name: 'userfile', //file的name
14         //当选择文件后执行的方法,ext存在文件后续,可以在这里判断文件格式
15         onChange: function (file, ext) {
16             //内容
17         },
18         //提交文件时执行,也可以在这里判断文件格式
19         onSubmit: function (file, ext) {
20             if (fileType == "pic") {
21                 if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)) {
22                     this.setData({
23                         'info': '文件类型为图片'
24                     });
25                 } else {
26                     $('<li></li>').appendTo('#example .files').text('非图片类型文件,请重传');
27                     return false;
28                 }
29             }
30 
31             button.text('文件上传中');
32 
33             if (fileNum == 'one')
34                 this.disable();
35             //显示上传中的代码
36             interval = window.setInterval(function () {
37                 var text = button.text();
38                 if (text.length < 14) {
39                     button.text(text + '.');
40                 } else {
41                     button.text('文件上传中');
42                 }
43             }, 200);
44         },
45         onComplete: function (file, response) {//文件提交完后执行
46             //var data = eval_r('(' + response + ')'); //转json
47             if (response != "success")
48                 alert(response);
49 
50             button.text('文件上传');
51 
52             window.clearInterval(interval);
53 
54             this.enable();
55 
56             if (response == "success");
57             $('<li></li>').appendTo('#example .files').text(file);
58         }
59     });
60 });
 1 //异步删除文件
 2 function DelFile(index) {
 3     $.post("/Controller/DelFile",
 4         { "imgurl": "", "RandomNumber": Math.random() },
 5         function (data, textStatus) {
 6             if (typeof (data.error) != null) {
 7                 //成功
 8             }
 9             else {
10                 //失败
11             }
12         }, "json");
13 }

 

注释: 第1行:$(document).ready()函数,Jquery中的函数,类似于window.load,使用这个函数可在DOM载入就绪能够读取并操纵时立即调用绑定的函数。

第3行:fileType和fileNum参数代表上传文件的类型和数量,默认值为可上传所有类型文件,同一时间只能上传一个文件,如想上传图片文件或同时上传多个文件,可将这两个变量值变为pic和more。

第6~8行:POST到服务器的数据,你可以设置静态值也可以通过Jquery的DOM操作函数获得一些动态值,比如form表单中INPUT的值等。

第9行:等同于前端

1 <input type="file" name="userfile">

服务器端$_FILES['userfile']

第10~36行:文件上传前触发的功能。

第11~21行:图片文件类型的过滤功能,Jquery setData函数用来设置POST至服务器端的值。

第25~26行:设置同时只上传一个文件还是多个文件,如果只上传一个文件,则将触发按钮禁掉。如果要多传输几个文件,请在服务器端PHP文件上传程序中设置MAXSIZE的值,当然上传文件的大小限制同时和PHP.INI文件中的设置也有关。

第28~35行:在文件上传过程中每隔200毫秒动态更新一次按钮的文字,已实现动态提示的效果。window.setInterval函数用来每隔指定的时间就执行一次内置的函数,交互时间单位为豪秒。

第37~49行:文件上传功能完成后触发的功能,根据返回值如果服务器端报错,则前端通过ALERT方式提示出错信息。

服务器端Controller文件上传代码

  

 1         public ActionResult upload()
 2         {
 3             string msg = string.Empty;
 4             string error = string.Empty;
 5             string name = string.Empty;
 6             string url = string.Empty;
 7             if (Request.Files.Count > 0)
 8             {
 9                 HttpPostedFileBase file = Request.Files[0];
10                 if (IsAllowedExtension(file))
11                 {
12                     if (file.ContentLength == 0)
13                         error = "文件长度为0";
14                     else
15                     {
16                         int UserId = GetUserId();
17                         string ImgPath = System.Configuration.ConfigurationManager.AppSettings["ImageFilePath"] + UserId + "/"
18                             + DateTime.Now.Year + "/" + DateTime.Now.Month + "/";
19                         string fileName = DateTime.Now.ToString("yyyyMMddhhmmss")
20                             + (new Random().Next(10, 1000)) + Path.GetExtension(file.FileName);//年 + 月 + 日
21 
22 
23                         string path = Server.MapPath(ImgPath);
24                         if (!Directory.Exists(path))
25                             Directory.CreateDirectory(path);
26                         file.SaveAs(path + fileName);
27                         msg = "上传成功";
28                         name = Path.GetFileNameWithoutExtension(file.FileName);
29                         url = ImgPath + fileName;
30                     }
31                 }
32                 else
33                 {
34                     error = "图片格式不正确!";
35                 }
36             }
37             else
38                 error = "请选择上传图片!";
39 
40 
41             StringBuilder result = new StringBuilder();
42             result.Append("{");
43             result.AppendFormat(""error":"{0}",", error);
44             result.AppendFormat(""msg":"{0}",", msg);
45             result.AppendFormat(""name":"{0}",", name);
46             result.AppendFormat(""url":"{0}"", url);
47             result.Append("}");
48             return Content(result.ToString(), "text/html");
49         }
50 
56         public ActionResult DelFile()
57         {
58             StringBuilder result = new StringBuilder();
59             string msg = "";
60             string error = "";
61             try
62             {
63                 //System.IO.File.Delete(Server.MapPath("~/" + Request.Form["imgurl"]));
64                 CommonClass.DelFile(Server.MapPath(Request.Form["imgurl"]));
65                 msg = "删除成功";
66             }
67             catch (Exception)
68             {
69                 error = "删除失败";
70             }
71             result.Append("{");
72             result.AppendFormat(""error":"{0}",", error);
73             result.AppendFormat(""msg":"{0}"", msg);
74             result.Append("}");
75             return Content(result.ToString(), "text/html");
76         }

 

posted @ 2012-09-17 23:55  鸿bi  阅读(1016)  评论(0编辑  收藏  举报