最近要做一个文件上传的东西 经过同事的推荐所以就选择了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);
            }
        }

到此就完成了。。。由于时间紧迫 就不废话了 从中引用了别人的代码 希望能帮到大家 谢谢!

plupload的一些使用心得的更多相关文章

  1. plupload 异步上传插件使用心得

    plupload 可以不依赖jquery,并且提供了 html5,flash,silverlight,html4 多种上传模式,使用起来比较简单,上一篇博客中介绍了其主要参数哈函数 一.简化用法 &l ...

  2. ASP.NET 使用 plupload 上传大文件时出现“blob”文件的Bug

    最近在一个ASP.NET 项目中使用了plupload来上传文件,结果几天后客户发邮件说上传的文件不对,说是文件无法打开 在进入系统进行查看后发现上传的文件竟然没有后缀,经过一番测试发现如果文件上传的 ...

  3. 我的MYSQL学习心得(一) 简单语法

    我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(五) 运 ...

  4. NoSql数据库使用半年后在设计上面的一些心得

    NoSql数据库这个概念听闻许久了,也陆续看到很多公司和产品都在使用,优缺点似乎都被分析的清清楚楚.但我心里一直存有一个疑惑,它的出现究竟是为了解决什么问题? 这个疑惑非常大,为此我看了很多分析文章, ...

  5. 我的MYSQL学习心得(二) 数据类型宽度

    我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(五) 运 ...

  6. 我的MYSQL学习心得(三) 查看字段长度

    我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(五) 运 ...

  7. 我的MYSQL学习心得(四) 数据类型

    我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(五) 运 ...

  8. 我的MYSQL学习心得(五) 运算符

    我的MYSQL学习心得(五) 运算符 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据 ...

  9. 我的MYSQL学习心得(六) 函数

    我的MYSQL学习心得(六) 函数 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类 ...

随机推荐

  1. SSIS的控制流之Foreach循环容器和序列容器

    上一篇介绍了For循环容器的使用.本篇将介绍Foreach循环容器和序列容器的使用. Foreach循环容器 Foreach循环容器定义包中的控制流.其循环的实现类似于编程语言中的Foreach循环结 ...

  2. 微信支付:微信支付遇到的坑:jssdk,phpdemo,微信支付提示{"errMsg":"chooseWXPay:fail"}

    微信支付:微信支付遇到的坑:jssdk,phpdemo 使用微信支付,真是变态,如果不是微信用户多,我才不适配微信支付,我就在想:为什么没人用我支付宝的[点点虫]呢.一个小小的“/”的误差,都调不起微 ...

  3. python 各种装饰器示例(python3)

    参考网址: Python中的各种装饰器详解_python_脚本之家http://www.jb51.net/article/63892.htm 一.函数式装饰器: 1.装饰器无参数,被装饰对象无参数 d ...

  4. asp.net上传文件大小限制

    <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedConte ...

  5. POJ - 2079:Triangle (旋转卡壳,求最大三角形)

    Given n distinct points on a plane, your task is to find the triangle that have the maximum area, wh ...

  6. [HihoCoder1413]Rikka with String

    vjudge 题意 给你一个串,问你把每个位置的字符替换成#后串中有多少本质不同的子串. \(n\le 3*10^5\) sol 首先可以计算出原串里面有多少本质不同的子串.显然就是\(\sum_{i ...

  7. [ Laravel 5.5 文档 ] 数据库操作 —— 在 Laravel 中轻松实现分页功能

     简介 在其他框架中,分页是件非常痛苦的事,Laravel 让这件事变得简单易于上手.Laravel 的分页器与查询构建器和 Eloquent ORM 集成在一起,并开箱提供方便的.易于使用的.基于 ...

  8. 让人蛋疼的“Oracle.DataAccess.dll”

    项目介绍:为前台网站提供rest接口来操作erp相关数据 涉及db:oracle11 技术方案:因为erp是用remoting来调用,我想rest实现部分调用remoting来操作减少耦合,当然性能上 ...

  9. C# partial 说明(转)

    http://www.cnblogs.com/Echo_saq/archive/2012/11/19/2777058.html 1. 什么是局部类型? C# 2.0 引入了局部类型的概念.局部类型允许 ...

  10. 修改windows文件的换行符

    应用场景: 在办公中,有可能存在,某些命令脚本使用windows下的文本编辑器进行编写 当放到测试环境的Linux中时,运行报错 需要使用的软件:xxd hexdump  dos2unix 1.运行w ...