上传系列:jquery.upload.js

最近想做一个上传的总结,把自己用过的上传插件都写一写,哪天用到的时候就不用再一次的翻阅资料,现在页面上用到的上传插件,原理上都差不多,那我也就不再废话了,下面我主要记录一下几个比较常用的,由简到繁,这里我只写代码,其它的就不在啰嗦了:

  • jquery.upload.js
  • ajaxupload.js
  • uploadify
  • SWFUpload

jquery.upload.js


  这里只写主要的,至于js的引用我就不用说了是吧,自己添加上就行,我就不写了。

  前台html代码:

 1 <html>
 2 <head>
 3     <meta name="viewport" content="width=device-width" />
 4     <title></title>
 5     <script>
 6         /*文件上传*/
 7         function upload() {
 8             $.upload({                      // 上传方法
 9                 url: '/System/Upload',      // 上传地址
10                 fileName: 'uploadfile',     // 文件域名字
11                 params: { name: 'pxblog' }, // 其他表单数据
12                 dataType: 'json',           // 上传完成后, 返回json, text
13                 onSend: function () {       // 上传之前回调,return true表示可继续上传
14                     return true;
15                 },
16                 onSubmit: function () {
17                 },
18                 onComplate: function (data) {   // 上传之后回调
19                     if (data.msg) {
20 
21                     } else {
22                         alert("上传图片出错!");
23                     }
24                 }
25             })
26         }
27     </script>
28 </head>
29 <body>
30     <div>
31         <input type="button" onclick="upload()" value="点击上传" />
32     </div>
33 </body>
34 </html>
View Code

  后台接收文件的代码,这里用的MVC

 1 public ActionResult Upload(HttpPostedFileBase FileData)
 2         {
 3             // 如果没有上传文件
 4             if (FileData == null || string.IsNullOrEmpty(FileData.FileName) || FileData.ContentLength == 0)
 5             {
 6                 return this.HttpNotFound();
 7             }
 8             string filename = Path.GetFileName(FileData.FileName);  //获得文件名
 9             string extension = Path.GetExtension(FileData.FileName);//获得文件扩展名
10             string phyPath = Request.MapPath("/Upload/");
11             if (!Directory.Exists(phyPath))
12             {
13                 Directory.CreateDirectory(phyPath);
14             }
15             decimal newid = Math.Abs(Guid.NewGuid().GetHashCode());
16             string filepath = phyPath + newid + extension;
17             FileData.SaveAs(filepath);
18             return Content(newid + extension);
19         }
View Code

  缺点:

  这种方式,有个缺点,而且还是在IE上,想想就郁闷,很多乱七八糟的问题都出现在IE上,微软咋就不能好好整整IE啊。

  如果咱们返回方式选择json的时候,IE有的版本会弹框提示下载,哎,遇到这种问题,也真是够倒霉的,没办法,自求多福吧

原文地址:https://www.cnblogs.com/jiaxa/p/3926758.html