plupload的一些使用心得


 最近要做一個文件上傳的東西 經過同事的推薦所以就選擇了plupload,挺強大的 由於項目框架為改動后的MVC 剛一開始破費周折 不過最后總算是完成了 廢話不多說了 粘出來代碼給大家參考吧!文件包大家去官網上面下載吧。下載地址http://www.plupload.com/

引用

<link rel="stylesheet" href="$webpath/library/js/plupload/css/plupload.queue.css"
        type="text/css" media="screen" />
    <script type="text/javascript" src="$webpath/library/js/plupload/jquery.min.js"></script>
    <script type="text/javascript" src="$webpath/library/js/plupload/jquery.plupload.queue.min.js"></script>
    <script type="text/javascript" src="$webpath/library/js/plupload/plupload.min.js"></script>
    <script type="text/javascript" src="$webpath/library/js/plupload/plupload.flash.min.js"></script>

前台頁面的代碼JS

$(function () {
            // 初始化Flash上傳插件
            $("#flash_uploader").pluploadQueue({
                runtimes: 'flash',     //使用Flash插件
                url: '/AJAX/uploadFiles.ashx',     //服務器端響應頁面
                max_file_size: '10mb', //最大文件限制
                chunk_size: '1mb',     //一次上傳數據大小
                unique_names: true,     //是否自動生成唯一名稱
                filters: [{ title: "All files", extensions: "doc,docx,ppt,pptx,xls,xlsx,vsd,pot,pps,rtf,wps,et,dps,pdf,txt,epub,rar" }
],
                // 縮放圖片
                resize: { width: 320, height: 240, quality: 80 },
                // SWF文件位置
                flash_swf_url: '$webpath/library/js/plupload/plupload.flash.swf',
                init: {
                    FileUploaded: function (up, file, info) {
                        //一個文件上傳成功
                        var res = $("#hid_FilePath").val();
                        var newres = "";
                        newres = res + info.response;
                        $("#hid_FilePath").val(newres);
                    },
                    Error: function (up, args) {
                        //發生錯誤
                        if (args.file) {
                            alert('[error] File:' + args.file);
                        } else {
                            alert('[error]' + args);
                        }
                    }
                }
            });
            // 這一塊主要是防止在上傳未結束前表單提交,具體大家可酌情修改編寫    
            $('form').submit(function (e) {
                var uploader = $('#uploader').pluploadQueue();  // 取得上傳隊列   
                if (uploader.files.length > 0) {  // 就是說如果上傳隊列中還有文件   
                    uploader.bind('StateChanged', function () {
                        if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                            $('form')[0].submit(); //表單提交
                        }
                    });
                    uploader.start();
                } else {
                    alert('隊列中必須至少要有一個文件!');
                }
                return false;
            });
        });
    </script>

我用的是一般處理程序來處理上傳的核心代碼的uploadFiles.ashx代碼

 /// <summary>
        /// Json數據序列化
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        private string toJson(Dictionary<string, string> dic)
        {
            return EbookServer_Common.Public.toJson(dic);
        }
        /// <summary>
        /// Json數據反序列化
        /// </summary>
        /// <param name="jsonList"></param>
        /// <returns></returns>
        private string toJsonArray(List<string> jsonList)
        {
            return EbookServer_Common.Public.toJsonArray(jsonList);
        }
        public void UploadFile(HttpContext context)
        {
            Dictionary<string, string> _dic = new Dictionary<string, string>();
            context.Response.CacheControl = "no-cache";
            string s_rpath = FileHelper.GetUploadPath();//@"E:\My Documents\Visual Studio 2008\WebSites\SWFUpload\demos\applicationdemo.net";


            string Datedir = DateTime.Now.ToString("yy-MM-dd");
            string updir = s_rpath + "\\" + Datedir;
            string returnstr = "";
            int filesize = 0;
            List<string> _arr = new List<string>();
            if (context.Request.Files.Count > 0)
            {
                try
                {

                    for (int j = 0; j < context.Request.Files.Count; j++)
                    {
                        Dictionary<string, string> _dic_info = new Dictionary<string, string>();
                        HttpPostedFile uploadFile = context.Request.Files[j];
                        int offset = Convert.ToInt32(context.Request["chunk"]); //當前分塊
                        int total = Convert.ToInt32(context.Request["chunks"]);//總的分塊數量
                        string name = context.Request["name"];
                        //文件沒有分塊
                        if (total == 1)
                        {

                            if (uploadFile.ContentLength > 0)
                            {
                                if (!Directory.Exists(updir))
                                {
                                    Directory.CreateDirectory(updir);
                                }
                                //  string fileId = DateTime.Now.ToString("yyyyMMddHHmmssfff") + uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf("."));
                                uploadFile.SaveAs(string.Format("{0}\\{1}", updir, name));
                                filesize = Convert.ToInt32(uploadFile.ContentLength / 1024);
                            }
                        }
                        else
                        {
                            //文件 分成多塊上傳
                            string fullname = WriteTempFile(uploadFile, offset, name);
                            if (total - offset == 1)
                            {
                                //如果是最后一個分塊文件 ,則把文件從臨時文件夾中移到上傳文件 夾中
                                System.IO.FileInfo fi = new System.IO.FileInfo(fullname);
                                if (!Directory.Exists(updir))
                                {
                                    Directory.CreateDirectory(updir);
                                }
                                string oldFullName = string.Format(@"{0}\\{1}", updir, name);
                                FileInfo oldFi = new FileInfo(oldFullName);
                                if (oldFi.Exists)
                                {
                                    //文件名存在則刪除舊文件
                                    oldFi.Delete();
                                }
                                fi.MoveTo(oldFullName);
                                filesize = Convert.ToInt32(fi.Length / 1024);
                            }
                        }
                        
                        string filePath = string.Format(@"\\upload\\{0}\\{1}", Datedir, name);
                        string fileName = name;
                        string fileSize = filesize.ToString();
                        returnstr = returnstr + fileName + "||" + filePath + "||" + fileSize + ",";
                    }
                    context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                    context.Response.Charset = "utf-8";
                    context.Response.AddHeader("content-type", "application/x-javascript");
                    context.Response.Write(returnstr.ToString());
                }
                catch (Exception ex)
                {
                    context.Response.Write("Message" + ex.ToString());
                }
            }
        }
        /// <summary>
        /// 保存臨時文件
        /// </summary>
        /// <param name="uploadFile"></param>
        /// <param name="chunk"></param>
        /// <returns></returns>
        private string WriteTempFile(HttpPostedFile uploadFile, int chunk, string name)
        {
            // string fileId = DateTime.Now.ToString("yyyyMMddHHmmssfff") + uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf("."));
            string tempDir = FileHelper.GetTempPath();
            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }
            string fullName = string.Format("{0}\\{1}.part", tempDir, name);
            if (chunk == 0)
            {
                //如果是第一個分塊,則直接保存
                uploadFile.SaveAs(fullName);
            }
            else
            {
                //如果是其他分塊文件 ,則原來的分塊文件,讀取流,然后文件最后寫入相應的字節
                FileStream fs = new FileStream(fullName, FileMode.Append);
                if (uploadFile.ContentLength > 0)
                {
                    int FileLen = uploadFile.ContentLength;
                    byte[] input = new byte[FileLen];

                    // Initialize the stream.
                    System.IO.Stream MyStream = uploadFile.InputStream;

                    // Read the file into the byte array.
                    MyStream.Read(input, 0, FileLen);

                    fs.Write(input, 0, FileLen);
                    fs.Close();
                }
            }
            return fullName;
        }

 

還有一個文件處理類 引用來的FileHelper.cs

    public FileHelper()
        {
            //
            //TODO: 在此處添加構造函數邏輯
            //
        }
        /// <summary>
        /// 獲取上傳目錄
        /// </summary>
        /// <returns></returns>
        public static string GetUploadPath()
        {
            string path = HttpContext.Current.Server.MapPath("~/");
            string dirname = GetDirName();
            string uploadDir = path + "\\" + dirname;
            CreateDir(uploadDir);
            return uploadDir;
        }
        /// <summary>
        /// 獲取臨時目錄
        /// </summary>
        /// <returns></returns>
        public static string GetTempPath()
        {
            string path = HttpContext.Current.Server.MapPath("~/");
            string dirname = GetTempDirName();
            string uploadDir = path + "\\" + dirname;
            CreateDir(uploadDir);
            return uploadDir;
        }
        private static string GetDirName()
        {
            return System.Configuration.ConfigurationManager.AppSettings["uploaddir"];
        }
        private static string GetTempDirName()
        {
            return System.Configuration.ConfigurationManager.AppSettings["tempdir"];
        }
        public static void CreateDir(string path)
        {
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
        }

到此就完成了。。。由於時間緊迫 就不廢話了 從中引用了別人的代碼 希望能幫到大家 謝謝!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM