在这之前在感谢园子好多大牛的文章,在这里就不列出来了。

进入正题。

svn检索https://github.com/moxiecode/plupload 获取到代码,这篇文章使用的是v2.1.8

主要功能:

1、多文件上传

2、分片上传

3、显示进度条

先看看项目结构

<style>
.trip-uploader .webuploader-container { float: left; position: relative; width: 20%; display: block; line-height: 1.4; background: #fff; border: 1px dashed #D2D1D6; border-radius: 6px; color: #ccc; padding: 15px 0; font-size: 13px; text-align: center; margin: 4px; cursor: pointer; }
.webuploader-pick { width: 100%; display: block; cursor: pointer; overflow: hidden; }
.trip-uploader .webuploader-container .icon-plus { width: 32px; height: 32px; display: block; margin: 10px auto; background: url(/images/upimagedefault.png) no-repeat; background-size: 32px; }
.upload-btn { position: absolute; top: 0px; left: 0px; width: 100%; height: 98%; overflow: hidden; z-index:; }
.file-item { width: 120px; height: 120px; float: left; position: relative; margin: 0 0 10px; padding: 4px; padding: 4px; line-height: 1.42857143; background-color: #fff; border: 1px solid #ddd; border-radius: 4px; -webkit-transition: border .2s ease-in-out; -o-transition: border .2s ease-in-out; transition: border .2s ease-in-out; }
.fancybox { display: block; overflow: hidden; background: #eee; height: 120px; }
.file-item img { height: 110px; }
.file-item .progress { position: absolute; right: 4px; bottom: 4px; left: 4px; height: 4px; overflow: hidden; z-index:; margin:; padding:; border-radius:; background: 0 0; }
.file-item .progress span { display: block; overflow: hidden; width:; height: 100%; background: url(/images/progress.png) repeat-x #06BD01; -webit-transition: width .2s linear; -moz-transition: width .2s linear; -o-transition: width .2s linear; -ms-transition: width .2s linear; transition: width .2s linear; -webkit-animation: progressmove 2s linear infinite; -moz-animation: progressmove 2s linear infinite; -o-animation: progressmove 2s linear infinite; -ms-animation: progressmove 2s linear infinite; animation: progressmove 2s linear infinite; -webkit-transform: translateZ(0); }
</style>
<form id="form1" runat="server">
<div>
<div class="trip-uploader" style="height: 160px;">
<div class="uploader-images-list">
</div>
<div class="webuploader-container">
<div id="coverPicker" class="webuploader-pick webuploader-pick-hover" style="position: relative;">
<i class="icon icon-plus"></i>上传图片<br />
(最多N张)
</div>
<div id="imgupload" class="upload-btn"></div>
</div>
</div>
</div>
</form>
 <script>
var $list = $(".uploader-images-list");
var uploader = new plupload.Uploader({ //实例化一个plupload上 传对象
browse_button: 'imgupload',
runtimes: 'html5,flash,silverlight,html4',
url: '/Core/UploadHandler.ashx',
flash_swf_url: '/js/plupload/Moxie.swf',
silverlight_xap_url: '/js/plupload/Moxie.xap',
filters: {
mime_types: [ //只允许上传图片文件
{ title: "图片文件", extensions: "jpg,gif,png" }
]
}
, prevent_duplicates: !1
, max_file_size: '10mb'
, chunk_size: '1mb'//分片上传一定要注意压缩的大小
//, resize: { width: 320, height: 240, quality: 90 }
, init:
{
PostInit: function (a) {
console.log("初始化完毕");
},
FilesAdded: function (uder, files) {
console.log("添加进队列");
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendimg(file.id);
}
uder.start();
},
BeforeUpload: function (uder, files) {
console.log("开始上传");
},
UploadProgress: function (uder, file) {
console.log("进度:[百分比:" + file.percent + ",状态:" + file.status + ",原始大小:" + file.origSize + ",已传:" + file.loaded + "]");
progress(file.id, file.percent);
},
UploadFile: function (uder) {
console.log(uder.id + "开始上传");
},
FileUploaded: function (uder, file, resObject) {
var result = resObject.response;
console.log("上传完成" + result);
var $fileitem = $("." + file.id)
$fileitem.find("img").attr("src", JSON.parse(result).data);
//移除进度条
$fileitem.find(".progress").remove();
},
ChunkUploaded: function (a, b, c) {
console.log("小片上传完成后");
},
UploadComplete: function (uder, files) {
alert("上传完毕");
},
Error: function () {
alert("ERROR");
}
} });
uploader.init(); //初始化 function appendimg(id, imgurl) {
var html = ' <div class="' + id + ' file-item"><a class="fancybox"> <img /> </a> </div>';
$(".uploader-images-list").append(html);
}
function progress(id, percent) {
var c = $list.find("." + id);
var d = c.find(".progress span");
d.length || (d = $('<p class="progress"><span></span></p>').appendTo(c).find("span"));
d.css("width", percent + "%")
} </script>

下面的是后台代码:

   /// <summary>
/// BaseHandler 的摘要说明
/// </summary>
public class BaseHandler : IHttpHandler, IRequiresSessionState
{
public HttpRequest Request
{
get
{
return HttpContext.Current.Request;
}
}
public HttpResponse Response
{
get
{
return HttpContext.Current.Response;
}
}
public void ProcessRequest(HttpContext context)
{
var data = ProcessResponse(context);
var newData = new { code = data.code, data = data.data, msg = data.msg };
context.Response.ContentType = "application/json";
string jsonData = JsonConvert.SerializeObject(newData);
context.Response.Write(jsonData);
}
/// <summary>
/// 定义输出函数
/// </summary>
/// <returns></returns>
protected virtual ResponseData ProcessResponse(HttpContext context)
{
ResponseData data = new ResponseData { code = ReturnCode.error, data = "" };
return data;
} public bool IsReusable
{
get
{
return false;
}
}
}
/// <summary>
/// 返回值
/// </summary>
public struct ResponseData
{
/// <summary>
/// 返回的状态码
/// </summary>
public ReturnCode code;
/// <summary>
/// 返回状态码对应的消息
/// </summary>
public string msg;
/// <summary>
/// 附加内容
/// </summary>
public object data;
}
/// <summary>
/// 操作代码 返回给前台JS
/// </summary>
public enum ReturnCode
{
/// <summary>
/// 失败 0
/// </summary>
error = ,
/// <summary>
/// 成功 1
/// </summary>
success = ,
/// <summary>
/// 其他 ,自定义状态 返回9
/// </summary>
other =
}

基类BaseHandler.ashx

 public class UploadHandler : BaseHandler
{
ResponseData responseData = new ResponseData()
{
code = ReturnCode.error,
msg = "未配置",
data = null
};
protected override ResponseData ProcessResponse(HttpContext context)
{
Response.CacheControl = "no-cache";
string dir = GetUploadPath();
if (Request.Files.Count > )
{
try
{
for (int j = ; j < Request.Files.Count; j++)
{
int offset = Convert.ToInt32(Request["chunk"]); //当前分块
int total = Convert.ToInt32(Request["chunks"]);//总的分块数量
string name = Request["name"];
HttpPostedFile uploadFile = Request.Files[j];
if (total == )
{
if (uploadFile.ContentLength > )
{
string extname = Path.GetExtension(uploadFile.FileName);//.jpg
string filename = uploadFile.FileName; //xx.jpg
string path = dir + RndNum() + extname;
uploadFile.SaveAs(context.Server.MapPath(path));
responseData.msg = "上传成功";
responseData.data = path;
}
}
else
{
//文件 分成多块上传
string tempPath = WriteTempFile(uploadFile, offset);
if (total - offset == )
{
//如果是最后一个分块文件 ,则把文件从临时文件夹中移到上传文件夹中 string extname = Path.GetExtension(name);//.jpg
string newPath = dir + RndNum() + extname;
System.IO.FileInfo fi = new System.IO.FileInfo(context.Server.MapPath(tempPath));//临时文件名
//把临时文件移动到新目录并重名
fi.MoveTo(context.Server.MapPath(newPath));
responseData.msg = "上传成功";
responseData.data = newPath;
}
else
{
responseData.msg = "上传成功";
responseData.data = tempPath;
}
}
}
}
catch (Exception ex)
{
responseData.msg = ex.Message;
responseData.data = ex.ToString();
} }
return responseData;
} /// <summary>
/// 保存临时文件-返回相对路径
/// </summary>
/// <param name="uploadFile">文件流</param>
/// <param name="chunk">第几个分块 从0开始</param>
/// <param name="context"></param>
/// <returns></returns>
private string WriteTempFile(HttpPostedFile uploadFile, int chunk)
{
string tempPath = GetTempPath() + uploadFile.FileName + ".part"; //临时相对路径
string saveTempPath = HttpContext.Current.Server.MapPath(tempPath);
if (chunk == )
{
uploadFile.SaveAs(saveTempPath); //如果是第一个分块,则直接保存
}
else
{
//如果是其他分块文件 ,则原来的分块文件,读取流,然后文件最后写入相应的字节
FileStream fs = new FileStream(saveTempPath, FileMode.Append);
if (uploadFile.ContentLength > )
{
int FileLen = uploadFile.ContentLength;
byte[] input = new byte[FileLen];
System.IO.Stream MyStream = uploadFile.InputStream;
MyStream.Read(input, , FileLen);
fs.Write(input, , FileLen);
fs.Close();
}
} return tempPath;
} /// <summary>
/// 该方法用于生成指定位数的随机数
/// </summary>
/// <param name="VcodeNum">参数是随机数的位数</param>
/// <returns>返回一个随机数字符串</returns>
public string RndNum(int VcodeNum)
{
string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
//string Vchar = "0,1,2,3,4,5,6,7,8,9";
string[] VcArray = Vchar.Split(',');//拆分成数组 string VNum = "";
seed++;
Random rand = new Random(seed);
for (int i = ; i < VcodeNum; i++)
{
VNum += VcArray[rand.Next(VcArray.Length - )];
}
return VNum;
}
private static int _seed = int.Parse(DateTime.Now.Ticks.ToString().Substring());
private static int seed { get { return _seed; } set { _seed = value; } } //获取存放路径
public static string GetUploadPath()
{
string path = HttpContext.Current.Server.MapPath("/upload/");
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
return "/upload/";
}
/// <summary>
/// 获取临时目录 相对路径
/// </summary>
/// <returns></returns>
public static string GetTempPath()
{
string path = GetUploadPath();
path = HttpContext.Current.Server.MapPath("/upload/temp/");
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
return "/upload/temp/";
}
}

上传类UploadHandler.ashx

源代码:

demoPlupload

plupload 上传组件的使用的更多相关文章

  1. Plupload上传组件 + javaweb实现上传源码以及DEMO

    Plupload 是一个Web浏览器上的界面友好的文件上传模块,可显示上传进度.图像自动缩略和上传分块.可同时上传多个文件: 上网找了很多Plupload的DEMO都无法正常使用, 而且Pluploa ...

  2. 前端上传组件Plupload使用指南

    我之前写过一篇文章<文件上传利器SWFUpload使用指南>,里面介绍了上传组件SWFUpload的使用方法,但现在随着html5技术的逐渐推广和普及,再去使用以flash为上传手段的SW ...

  3. Plupload文件上传组件使用API

    Plupload有以下功能和特点: 1.拥有多种上传方式:HTML5.flash.silverlight以及传统的<input type=”file” />.Plupload会自动侦测当前 ...

  4. 【转】前端上传组件Plupload

    [转自博客园-无双] html5原生的给我们提供了文件上传的API,Plupload是一款由著名的web编辑器TinyMCE团队开发的上传组件,简单易用且功能强大,我们完全可以使用Plupload来代 ...

  5. 【转】前端上传组件Plupload使用指南

    http://www.cnblogs.com/2050/p/3913184.html Plupload有以下功能和特点: 1.拥有多种上传方式:HTML5.flash.silverlight以及传统的 ...

  6. web 文件上传组件 Plupload

    Plupload官网:点击打开链接   建议下载最新版本号,低版本号会出现浏览器兼容问题. 近期公司有个项目须要在web端使用多文件上传功能.刚開始准备使用HTML5来做.但是IE9下面是都不支持的, ...

  7. [Pulgin] 前端上传组件Plupload使用指南

    我之前写过一篇文章<文件上传利器SWFUpload使用指南>,里面介绍了上传组件SWFUpload的使用方法,但现在随着html5技术的逐渐推广和普及,再去使用以flash为上传手段的SW ...

  8. 前端上传组件 - Plupload

    http://www.cnblogs.com/KTblog/p/4740852.html 效果: 起始界面. ------------- 可以上上传单个文件. ------------- 可以上传多个 ...

  9. Flash上传组件之SWFUpload文件上传

    一.什么是SWFUpload? SWFUpload是一个客户端文件上传工具,最初由Vinterwebb.se开发,它通过整合Flash与JavaScript技术为WEB开发者提供了一个具有丰富功能继而 ...

随机推荐

  1. 为什么有时候访问某些加密https网站是不需要证书的? https? ssl?

    根证书是CA颁发给自己的证书, 是信任链的起点 1.所有访问https的网站都是需要证书的. 2.对于某些网站,尤其是证书颁发机构的网站,操作系统自动添加了这些网站访问需要的证书到证书管理器中,所以就 ...

  2. Ubuntu实用软件安装[转]

    Gedit编辑器配置 Ubuntu14.04从安装软件到卸载软件,删除安装包 linux wget 命令用法详解(附实例说明) ==================================== ...

  3. 【CF938G】Shortest Path Queries(线段树分治,并查集,线性基)

    [CF938G]Shortest Path Queries(线段树分治,并查集,线性基) 题面 CF 洛谷 题解 吼题啊. 对于每个边,我们用一个\(map\)维护它出现的时间, 发现询问单点,边的出 ...

  4. Mininet 系列实验(五)

    实验内容 实现一个单个交换机的拓扑,添加一个交换机,和N个主机到网络中.交换机和主机之间的每个链路能够设置带宽.延迟时间.以及丢包率.创建一个包含一个交换机和四个主机的网络,使用iperf测试主机之间 ...

  5. 【BZOJ2813】奇妙的Fibonacci

    Description ​ Fibonacci数列是这样一个数列: F1 = 1, F2 = 1, F3 = 2 . . . Fi = Fi-1 + Fi-2 (当 i >= 3) ​ pty忽 ...

  6. Andorid APK反逆向

    Andorid APK反逆向解决方案---梆梆加固原理探寻http://blog.csdn.net/androidsecurity/article/details/8892635 Android AP ...

  7. python3.6关键字总结

    模块是个好东西 import keyword # 导入关键字模块 lst = keyword.kwlist # 实例化 print(lst) # 看看有哪些玩意 print(len(lst)) # 貌 ...

  8. Docker入门与应用系列(四)数据卷管理

    一.介绍 Docker镜像是由多个文件系统(只读层)叠加而成.当我们启动一个容器的时候,Docker会加载只读镜像层并在其上(译者注:镜像栈顶部)添加一个读写层.如果运行中的容器修改了现有的一个已经存 ...

  9. bzoj千题计划142:bzoj3144: [Hnoi2013]切糕

    http://www.lydsy.com/JudgeOnline/problem.php?id=3144 如果D=2 ,两个点,高度为4,建图如下 #include<queue> #inc ...

  10. 100 Most Popular Machine Learning Video Talks

    100 Most Popular Machine Learning Video Talks 26971 views, 1:00:45,  Gaussian Process Basics, David ...