ajax上传文件的原理与实现

    ajax已经很普遍了,但使用 ajax上传文件自己却一直都没有涉及,我只知道挺复杂的,上传文件不同于上传一般的表单数据,必须特殊处理,知道一般ajax使用上传都是应用一个虚拟的iframe,但由于项目需要,在网上找了找,没想到找到了两个支持ajax上传文件的jquery插件,jquery.uploadify.js和dropzone.min.js两个都可以实现ajax上传文件,效果也不错。


1使用jquery.uploadify.js上传文件

 这种上传方式,使用了Flash,因此需要引用一个特殊的js文件swfobject.js,低版本的需要引用,高版本的这个文件已经包含在jquery.uploadify.js中了。另外低版本的参数和高版本的参数也不太一样了。

使用Uploadify v3.2.1的完整前台代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
    <script src="Styles/jquery.uploadify.js" type="text/javascript"></script>
    <link href="Styles/uploadify.css" rel="stylesheet" type="text/css" />
     <script type="text/javascript">
         $(document).ready(function () {

             $("#uploadify").uploadify({
                 swf: 'Styles/uploadify.swf',
                 uploader: 'Handler1.ashx?OperationType=upfile',//后台的处理地址
                 fileTypeDesc: '请选择excel文件',
                 buttonText: '请选择excel文件',
                 fileTypeExts: '*.xls',
                 'auto': false,
                  onSelectError: function (file, errorCode, errorMsg) {
                     switch (errorCode) {
                         case -100:
                             alert("上传的文件数量已经超出系统限制的" + $('#uploadify').uploadify('settings', 'queueSizeLimit') + "个文件!");
                             break;
                         case -110:
                             alert("文件 [" + file.name + "] 大小超出系统限制的" + $('#uploadify').uploadify('settings', 'fileSizeLimit') + "大小!");
                             break;
                         case -120:
                             alert("文件 [" + file.name + "] 大小异常!");
                             break;
                         case -130:
                             alert("文件 [" + file.name + "] 类型不正确!");
                             break;
                     }
                 },
                 onFallback: function () {
                     alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
                 },
                 //上传到服务器,服务器返回相应信息到data里  
                 onUploadSuccess: function (file, data, response) {
                     alert(data);
                 },
                 onSelect: function (fileObj) {
                     alert("文件名:" + fileObj.name + "\r\n" +
                  "文件大小:" + fileObj.size + "\r\n" +
                  "创建时间:" + fileObj.creationdate + "\r\n" +
                  "最后修改时间:" + fileObj.modificationdate + "\r\n" +
                  "文件类型:" + fileObj.type
            );
                 } 
             });            
         });
         function doUplaod() {
             $('#uploadify').uploadify('upload', '*');
         }

         function closeLoad() {
             $('#uploadify').uploadify('cancel', '*');
         }
     </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <div>
     <div id="fileQueue"></div>
    <input type="file" name="uploadify" id="uploadify" />
    <p>
      <a href="javascript:doUplaod()">上传</a>| 
      <a href="javascript:closeLoad()">取消上传</a>
    </p>
    </div>
    </div>
    </form>
</body>
</html>


Uploadify v2.1.0的写法

由于没有swfobject.js,需要添加引用

    <script src="Scripts/swfobject.js" type="text/javascript"></script>
另外部分参数也不一样,例如uploader,script

完整的前台代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.uploadify.v2.1.0.js" type="text/javascript"></script>

    <link href="Scripts/uploadify.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/swfobject.js" type="text/javascript"></script>
    <script type="text/javascript">

        
            </script>
            <script type="text/javascript">
                $(document).ready(function () {
                    $("#uploadify").uploadify({
                        'uploader': 'Scripts/uploadify1.swf',
                        'script': 'Handler1.ashx?OperationType=upfile',
                        'cancelImg': 'Scripts/cancel.png',
                        'folder': 'UploadFile',
                        'queueID': 'fileQueue',
                        'auto': false,
                        'multi': false,
                      
                        'fileExt': '*.doc;*.xls',
                        'fileDesc': '请选择excel文件',
                        'onSelect': function (e, queueId, fileObj) {
                            alert("唯一标识:" + queueId + "\r\n" +
                  "文件名:" + fileObj.name + "\r\n" +
                  "文件大小:" + fileObj.size + "\r\n" +
                  "创建时间:" + fileObj.creationDate + "\r\n" +
                  "最后修改时间:" + fileObj.modificationDate + "\r\n" +
                  "文件类型:" + fileObj.type
            );
                        }
                    });
                });  
            </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
     <div id="fileQueue"></div>
    <input type="file" name="uploadify" id="uploadify" />
    <p>
      <a href="javascript:$('#uploadify').uploadifyUpload()">上传</a>| 
      <a href="javascript:$('#uploadify').uploadifyClearQueue()">取消上传</a>
    </p>
    </div>
    </form>
</body>
</html>

2使用dropzone.min.js上传文件

没有使用Flash,但对浏览器要求比较高,例如IE10以上才支持,应该是使用了html5的技术

完整的前端代码、

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
    <script src="Scripts/dropzone.min.js" type="text/javascript"></script>
    <link href="Scripts/dropzone.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        jQuery(function ($) {
            Dropzone.autoDiscover = false;
            try {
                var myDropzone = new Dropzone("#dropzone", {
                    paramName: "FileData", // The name that will be used to transfer the file
                    maxFilesize: 5, // MB
                    dictRemoveFile: '移除文件',
                    dictCancelUpload: '取消上传',
                    addRemoveLinks: true,
                    uploadMultiple: false,
                    acceptedFiles: '.xls',
                    autoProcessQueue: true,
                    dictRemoveFile: "关闭",
                    dictFileTooBig: '此文件过大',
                    dictCancelUploadConfirmation: '确定取消上传吗?',
                    dictInvalidInputType: "不支持此类型文件上传!",
                    parallelUploads: 1, //限制上传文件数
                    url: "Handler1.ashx?OperationType=upfile",
                    init: function () {
                        this.on("success", function (file) {
                            //console.log("File " + file.name + "uploaded");
                            alert("文件" + file.name + "上传成功");                       
                        });
                        this.on("complete", function (file) {
                            this.removeFile(file);
                        });
                        this.on("removedfile", function (file) {
                            //alert(file.name);
                        });
                    },
                  /*  accept: function (file, done) {
                        //if (file.name == "11.jpg") {
                        //    done("Naha, you don't.");
                        //}
                        //else {
                        done();
                    },*/
                    success: function (file, data) {
                        if (data.status === 1) {
                            $scope.uploadImage = data.message;
                            $scope.listUserImages();
                        } else {
                            //alertService.showAlert({
                            //    content: data.message,
                            //    type: 'warning'
                            //});
                            //$('.dz-error-mark').show();
                            //alert(data.message);
                        }
                    },
                    dictDefaultMessage:
                    '<span class="bigger-150 bolder"><i class="ace-icon fa fa-caret-right red"></i> 上传</span> 文件 \<span class="smaller-80 grey">点击</span> <br /> \<i class="upload-icon ace-icon fa fa-cloud-upload blue fa-3x"></i>',
                    dictResponseError: 'Error while uploading file!',
                    //change the previewTemplate to use Bootstrap progress bars
                    previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n  <div class=\"dz-details\">\n    <div class=\"dz-filename\"><span data-dz-name></span></div>\n    <div class=\"dz-size\" data-dz-size></div>\n    <img data-dz-thumbnail />\n  </div>\n  <div class=\"progress progress-small progress-striped active\"><div class=\"progress-bar progress-bar-success\" data-dz-uploadprogress></div></div>\n  <div class=\"dz-success-mark\"><span></span></div>\n  <div class=\"dz-error-mark\"><span></span></div>\n  <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>"
                });
            } catch (e) {
                alert('Dropzone.js does not support older browsers!');
            }
        });
    </script>
</head>
<body>
    <form id="dropzone" runat="server" action="Handler1.ashx?OperationType=upfile" class="dropzone dz-clickable"  enctype="multipart/form-data" method="post">
     <div class="dz-message" style="width:50px;height:50px;">
      <i class="upload-icon ace-icon fa fa-cloud-upload blue fa-3x"></i>
        </div>
    <div>

<div id="FileBed"></div>点击上传文件
  <input type="file" multiple="multiple" class="dz-hidden-input" style="visibility: hidden; position: absolute; top: 0px; left: 0px; height: 0px; width: 0px;" />
    </div>
    </form>
    
</body>
</html>

3后台处理代码

 public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
             string operatype = context.Request.QueryString["OperationType"];
             if (operatype == "upfile")
             {
                 HttpPostedFile file = context.Request.Files["FileData"];
                 if (file != null)
                 {
                     string fullPath = System.IO.Path.Combine(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "update"), DateTime.Now.Date.ToString("yyyyMMdd"));
                     file.SaveAs(fullPath + file.FileName);                 
                 }
             }
            context.Response.ContentType = "text/plain";
            context.Response.Write("上传成功");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }



源代码下载



你可能感兴趣的:(ajax上传文件的原理与实现)