说明:Plupload!
WEBFileUploadwindows本人在2010swfupload为核心进行文件的批量上传的解决方案。见文章:WEB版一次选择多个文件进行批量上传(swfupload)的解决方案。
swfupload示例IE9随着HTML5IE9IE10swfuploadplupload
Web,同时上传多个文件。的上传文件的引擎使用FlashSilverlightHTML5,Gears,BrowserPlus的FileUpload。
Feature | Flash | Gears | Silverlight | BrowserPlus | ||
Chunking | √ | √ | √1 | √ | √ | X |
Drag/Drop | X | √ | √2 | X | √ | X |
√ | √ | √3 | √ | √ | X | |
√ | √ | √3 | √ | √ | X | |
√ | √ | √4 | √ | √ | X | |
√ | √ | √ | √ | X | X | |
√ | √ | √5 | √ | √ | √ | |
√ | √ | √ | √ | √ | X | |
√ | √ | √ | √ | √ | X | |
√ | √ | √ | √ | X | X |
关于上表中的一些注意点说明:
文件拖放功能目录只适用于Firefox和WebKit。Safari在Windows上有一些奇怪的问题,需要解决。
多部分上传仅支持在Gecko和WebKit。
FlashSilverlightHTML5,Gears,BrowserPlus、FileUpload上传文件技术引擎。
PluploadAPI
jgp;gif
Plupload官方网站:http://www.plupload.com/
的批量文件解决方案。
让我们先来看看客户端的界面效果图。(多选文件,批量上传,上传进度显示)
ͼ1
2
3
4
二:具体的代码与操作步骤:
第一步,要进行下面的过程,必须先准备好Plupload组件。
Plupload官方网站:http://www.plupload.com/demo
第二步,
1.
js
第三步,前台部分准备客户操作的WEB[WebUploadFileTest2.aspx、uploadFiles.ashx]
WebUploadFileTest2.aspx的代码如下,WebUploadFileTest2.aspx.cs
WebUploadFileTest2.aspx
Html
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebUploadFileTest2.aspx.cs" Inherits="WebApplication1.WebUploadFileTest2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>多文件上传</title>
<!-- Load Queue widget CSS and jQuery -->
<style type="text/css">@import url(Scripts/jquery.ui.plupload/css/jquery.ui.plupload.css);</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/base/jquery-ui.css"/>
<!-- Third party script for BrowserPlus runtime (Google Gears included in Gears runtime now) -->
<script type="text/javascript" src="http://bp.yahooapis.com/2.4.21/browserplus-min.js"></script>
<!-- Load plupload and all it's runtimes and finally the jQuery UI queue widget -->
<script type="text/javascript" src="Scripts/plupload.full.js"></script>
<script type="text/javascript" src="Scripts/jquery.ui.plupload/jquery.ui.plupload.js"></script>
<script type="text/javascript">
// Convert divs to queue widgets when the DOM is ready
$(function () {
$("#uploader").plupload({
// General settings
runtimes: 'gears,flash,silverlight,browserplus,html5', // 这里是说用什么技术引擎
url: 'uploadFiles.ashx', // 服务端上传路径
max_file_size: '10mb', // 文件上传最大限制。
chunk_size: '1mb', // 上传分块每块的大小,这个值小于服务器最大上传限制的值即可。
unique_names: true, // 上传的文件名是否唯一
// Resize images on clientside if we can
//// 是否生成缩略图(仅对图片文件有效)
resize: { width: 320, height: 240, quality: 90 },
// Specify what files to browse for
//// 这个数组是选择器,就是上传文件时限制的上传文件类型
filters: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip,rar,7z" }
],
// Flash settings
// plupload.flash.swf 的所在路径
flash_swf_url: 'Scripts/plupload.flash.swf',
// Silverlight settings
// silverlight所在路径
silverlight_xap_url: 'Scripts/plupload.silverlight.xap'
});
// Client side form validation
$('form').submit(function (e) {
var uploader = $('#uploader').plupload('getUploader');
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else
alert('You must at least upload one file.');
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>一次选择多个文件进行上传</h2>
</div>
<div id="uploader" style="width: 600px">
<p>You browser doesn't have Flash, Silverlight, Gears, BrowserPlus or HTML5 support.</p>
</div>
</form>
</body>
</html>
以上代码最后的显示结果如图:
.
2)uploadFiles.ashxuploadFiles.ashx.cs
/// <summary>
/// uploadFiles 的摘要说明
/// </summary>
public class uploadFiles : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
UploadFile(context);
}
public bool IsReusable
{
get
{
return false;
}
}
public void UploadFile(HttpContext context)
{
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 extname = string.Empty;
string fullname = string.Empty;
string filename = string.Empty;
if (context.Request.Files.Count > 0)
{
try
{
for (int j = 0; j < context.Request.Files.Count; j++)
{
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);
}
extname = Path.GetExtension(uploadFile.FileName);
fullname = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
filename = uploadFile.FileName;
uploadFile.SaveAs(string.Format("{0}\\{1}", updir, filename));
}
}
else
{
//文件 分成多块上传
fullname = WriteTempFile(uploadFile, offset);
if (total-offset==1)
{
//如果是最后一个分块文件 ,则把文件从临时文件夹中移到上传文件 夹中
System.IO.FileInfo fi = new System.IO.FileInfo(fullname);
string oldFullName = string.Format("{0}\\{1}", updir, uploadFile.FileName);
FileInfo oldFi = new FileInfo(oldFullName);
if (oldFi.Exists)
{
//文件名存在则删除旧文件
oldFi.Delete();
}
fi.MoveTo(oldFullName);
}
}
}
}
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 tempDir = FileHelper.GetTempPath();
if (!Directory.Exists(tempDir))
{
Directory.CreateDirectory(tempDir);
}
string fullName = string.Format("{0}\\{1}.part", tempDir, uploadFile.FileName);
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;
}
}
第四步:文件辅助类
/// <summary>
///FileHelper 的摘要说明
/// </summary>
public class FileHelper
{
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);
}
}
}
第五步,在进行上传之后,图片文件进行缩略图保存。如下图。
第六步:以上都是英文界面,可以添加中文语言包。代码如下。
<!-- Load Queue widget CSS and jQuery -->
<style type="text/css">@import url(Scripts/jquery.ui.plupload/css/jquery.ui.plupload.css);</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/base/jquery-ui.css"/>
<!-- Third party script for BrowserPlus runtime (Google Gears included in Gears runtime now) -->
<script type="text/javascript" src="http://bp.yahooapis.com/2.4.21/browserplus-min.js"></script>
<!-- Load plupload and all it's runtimes and finally the jQuery UI queue widget -->
<script type="text/javascript" src="Scripts/plupload.full.js"></script>
<script type="text/javascript" src="Scripts/i18n/zh-cn.js"></script> //这一句是重点,添加中文语言包文件
<script type="text/javascript" src="Scripts/jquery.ui.plupload/jquery.ui.plupload.js"></script>
添加中文语言包之后的界面显示如下图:
上传错误信息:
一共有两个文件 :WebUploadFileTest2.aspx示例是上文中给出的代码示例文件 。
WebUploadFileTest.aspx是另一个示例文件 。
转载请注明本文地址:WEB版一次选择多个文件进行批量上传(Plupload)的解决方案