Uploadify 是一個基於 jQuery 的經典文件上傳插件,它能提供多文件上傳與實時進度條,界面友好。下面是一個完整的實現示例。
首先引入 Uploadify 相關的 CSS 與 JS 文件,並在 uploadify() 方法中完成各項配置:
<link href="js/jquery.uploadify-v2.1.4/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.uploadify-v2.1.4/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery.uploadify-v2.1.4/swfobject.js"></script>
<script type="text/javascript" src="js/jquery.uploadify-v2.1.4/jquery.uploadify.v2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#uploadify").uploadify({
'uploader': 'js/jquery.uploadify-v2.1.4/uploadify.swf', // swf 文件路徑
'script': 'UploadHandler.ashx', // 處理上傳的後台腳本
'cancelImg': 'js/jquery.uploadify-v2.1.4/cancel.png',
'folder': 'UploadFile/<% = subpathName %>', // 上傳文件夾
'queueID': 'fileQueue', // 文件隊列元素 id
'auto': false, // 添加文件後是否自動上傳
'multi': true, // 是否允許多文件上傳
'fileExt': '*.jpg;*.gif;*.png', // 允許上傳的後綴
'fileDesc': 'Web Image Files (.JPG, .GIF, .PNG)', // 文件類型提示文本
'sizeLimit': 102400, // 文件大小限制,單位字節(此處約 100K)
'onCancel': function (event, ID, fileObj, data) {
alert('The upload of ' + fileObj.name + ' has been canceled!');
},
'onComplete': function (event, ID, fileObj, response, data) {
alert('There are ' + data.fileCount + ' files remaining in the queue.');
},
'onAllComplete': function (event, data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
});
});
</script>
body 中需要一個用於顯示隊列的容器、文件選擇框,以及上傳與取消的觸發鏈接:
<div id="fileQueue"></div>
<input type="file" name="uploadify" id="uploadify" />
<p>
<a href="javascript:$('#uploadify').uploadifyUpload()">上傳</a>|
<a href="javascript:$('#uploadify').uploadifyClearQueue()">取消上傳</a>
</p>
後台使用 ashx 一般處理程序接收上傳的文件,並保存到指定目錄:
<%@ WebHandler Language="C#" Class="UploadHandler" %>
using System;
using System.Web;
using System.IO;
public class UploadHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
HttpPostedFile file = context.Request.Files["Filedata"];
string uploadPath = HttpContext.Current.Server.MapPath(context.Request["folder"]);
if (file != null) {
if (!Directory.Exists(uploadPath)) {
Directory.CreateDirectory(uploadPath);
}
file.SaveAs(Path.Combine(uploadPath, file.FileName));
context.Response.Write("1"); // 上傳成功
} else {
context.Response.Write("0"); // 上傳失敗
}
}
public bool IsReusable {
get { return false; }
}
}
通過以上配置,即可實現帶有實時進度條的多文件上傳功能,並在關鍵節點給出友好提示。