一聚教程网:一个值得你收藏的教程网站

热门教程

jquery jaxFileUpload文件上传插件使用详解

时间:2022-06-25 17:26:30 编辑:袖梨 来源:一聚教程网

jaxFileUpload简介

ajaxFileUpload插件是一个非常简单的基于Jquery的异步上传文件的插件,使用过程中发现很多与这个同名的,基于原始版本基础之上修改过的插件,文件版本比较多,我把我自己使用的ajaxFileUpload文件上传到博客园上了,想要使用的朋友可以下载:/ajaxfileupload.js。

整个插件源码不到200行,实现非常简单,大致原理就是通过js动态创建隐藏的表单,然后进行提交操作,达到附件上传的目的,主要实现在源码里都有注释,不难理解,我们也可以基于此简单版本实现更复杂的操作。

ajaxFileUpload使用说明

ajaxFileUpload的使用也很简单,调用ajaxFileUpload方法即可,各配置项详细说明如下:


$.ajaxFileUpload({
          type: "post",                          //请求类型:post或get,当要使用data提交自定义参数时一定要设置为post
          url: "/Shared/Upload",                 //文件上传的服务器端请求地址
            secureuri: false,                      //是否启用安全提交,一般默认为false就行,不用特殊处理
            fileElementId: "filePicture",          //文件上传控件的id  
          dataType: "json",                      //返回值类型,一般设置为json,还支持htmlxmlscript类型
            data: { "id": "1", "name": "test" },   //用于post请求提交自定义参数
            success: function (data, status) {     //服务器成功响应处理函数
            },
            error: function (data, status, e) {    //服务器响应失败处理函数
            }
        });

首先在页面添加对JQuery及ajaxFileUpload的引用,这里的JQuery用的2.1.4版本,经测试用各个版本基本没什么影响。


页面添加类型为file的input标签

通过accept可以限定打开文件选择对话框后,默认能选择的文件类型。文件类型的定义主要有以下这些


*.3gpp  audio/3gpp, video/3gpp  3GPP Audio/Video

*.ac3   audio/ac3   AC3 Audio

*.asf   allpication/vnd.ms-asf  Advanced Streaming Format

*.au    audio/basic AU Audio

*.css   text/css    Cascading Style Sheets

*.csv   text/csv    Comma Separated Values

*.doc   application/msword  MS Word Document

*.dot   application/msword  MS Word Template

*.dtd   application/xml-dtd Document Type Definition

*.dwg   image/vnd.dwg   AutoCAD Drawing Database

*.dxf   image/vnd.dxf   AutoCAD Drawing Interchange Format

*.gif   image/gif   Graphic Interchange Format

*.htm   text/html   HyperText Markup Language

*.html  text/html   HyperText Markup Language

*.jp2   image/jp2   JPEG-2000

*.jpe   image/jpeg  JPEG

*.jpeg  image/jpeg  JPEG

*.jpg   image/jpeg  JPEG

*.js    text/javascript, application/javascript JavaScript

*.json  application/json    JavaScript Object Notation

*.mp2   audio/mpeg, video/mpeg  MPEG Audio/Video Stream, Layer II

*.mp3   audio/mpeg  MPEG Audio Stream, Layer III

*.mp4   audio/mp4, video/mp4    MPEG-4 Audio/Video

*.mpeg  video/mpeg  MPEG Video Stream, Layer II

*.mpg   video/mpeg  MPEG Video Stream, Layer II

*.mpp   application/vnd.ms-project  MS Project Project

*.ogg   application/ogg, audio/ogg  Ogg Vorbis

*.pdf   application/pdf Portable Document Format

*.png   image/png   Portable Network Graphics

*.pot   application/vnd.ms-powerpoint   MS PowerPoint Template

*.pps   application/vnd.ms-powerpoint   MS PowerPoint Slideshow

*.ppt   application/vnd.ms-powerpoint   MS PowerPoint Presentation

*.rtf   application/rtf, text/rtf   Rich Text Format

*.svf   image/vnd.svf   Simple Vector Format

*.tif   image/tiff  Tagged Image Format File

*.tiff  image/tiff  Tagged Image Format File

*.txt   text/plain  Plain Text

*.wdb   application/vnd.ms-works    MS Works Database

*.wps   application/vnd.ms-works    Works Text Document

*.xhtml application/xhtml+xml   Extensible HyperText Markup Language

*.xlc   application/vnd.ms-excel    MS Excel Chart

*.xlm   application/vnd.ms-excel    MS Excel Macro

*.xls   application/vnd.ms-excel    MS Excel Spreadsheet

*.xlt   application/vnd.ms-excel    MS Excel Template

*.xlw   application/vnd.ms-excel    MS Excel Workspace

*.xml   text/xml, application/xml   Extensible Markup Language

*.zip   aplication/zip  Compressed Archive


我这里没有单独放上传按钮,添加了onchange事件,在选择文件后立即上传文件,onchange时间定义如下。

function filePictureChange() {
            $.ajaxFileUpload({
                url: "/Shared/Upload", //用于文件上传的服务器端请求地址
                   type: "post",
                secureuri: false, //一般设置为false
                fileElementId: "filePicture", //文件上传空间的id属性
                   dataType: "json", //返回值类型 一般设置为json
                success: function (data, status) {  //服务器成功响应处理函数
                       alert(data.fileName);
                    alert(data.filePath);
                    alert(data.fileSize);
                },
                error: function (data, status, e){  //服务器响应失败处理函数
                       alert(e);
                }
            });
        };

后台控制器处理方法如下,使用MD5处理,判断文件是否已经存在,避免文件重复上传。


///


        /// 附件上传
        ///

        ///
        public ActionResult Upload()
        {
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            if (files.Count == 0) return Json("Faild", JsonRequestBehavior.AllowGet);
            MD5 md5Hasher = new MD5CryptoServiceProvider();
            /*计算指定Stream对象的哈希值*/
            byte[] arrbytHashValue = md5Hasher.ComputeHash(files[0].InputStream);
            /*由以连字符分隔的十六进制对构成的String,其中每一对表示value中对应的元素;例如“F-2C-4A”*/
            string strHashData = System.BitConverter.ToString(arrbytHashValue).Replace("-", "");
            string FileEextension = Path.GetExtension(files[0].FileName);
            string uploadDate = DateTime.Now.ToString("yyyyMMdd");
            string virtualPath = string.Format("/Data/ComponentAttachments/{0}/{1}{2}", uploadDate, strHashData, FileEextension);
            string fullFileName = Server.MapPath(virtualPath);
            //创建文件夹,保存文件
              string path = Path.GetDirectoryName(fullFileName);
            Directory.CreateDirectory(path);
            if (!System.IO.File.Exists(fullFileName))
            {
                files[0].SaveAs(fullFileName);
            }
            string fileName = files[0].FileName.Substring(files[0].FileName.LastIndexOf("\") + 1, files[0].FileName.Length - files[0].FileName.LastIndexOf("\") - 1);
            string fileSize = GetFileSize(files[0].ContentLength);
            return Json(new { FileName = fileName, FilePath = virtualPath, FileSize = fileSize }, "text/html", JsonRequestBehavior.AllowGet);
        }
        ///
        /// 获取文件大小
        ///

        ///
        ///
        private string GetFileSize(long bytes)
        {
            long kblength = 1024;
            long mbLength = 1024 * 1024;
            if (bytes < kblength)
                return bytes.ToString() + "B";
            if (bytes < mbLength)
                return decimal.Round(decimal.Divide(bytes, kblength), 2).ToString() + "KB";
            else
                return decimal.Round(decimal.Divide(bytes, mbLength), 2).ToString() + "MB";
        }


2 ajaxFileUpload使用过程中的一些问题

2.0 jQuery.handleError is not a function

解决方法:

经测试handlerError只在jquery-1.4.2之前的版本中存在,以后版本中都没有这个函数了,因此在将handleError这个函数复制到ajaxFileUpload.js中,就行了

   uploadHttpData: function (r, type) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if (type == "script")
            jQuery.globalEval(data);
        // Get the JavaScript object, if JSON is used.
        if (type == "json")
            eval("data = " + data);
            //eval("data = "" + data + """);
        // evaluate scripts within html
        if (type == "html")
            jQuery("

").html(data).evalScripts();

        return data;
    },
    handleError: function (s, xhr, status, e) {
        // If a local callback was specified, fire it
        if (s.error) {
            s.error.call(s.context || s, xhr, status, e);
        }

        // Fire the global callback
        if (s.global) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
        }
    }