原址:http://www.cnblogs.com/chillsrc/archive/2010/02/21/1670594.html
這裏,就將針對這個問題提出一個比較完美的解決方案,利用的SwfUpload組件,讓客戶一次選擇多個文件,然後將選擇的文件上傳到服務器上。
關於SWFUpload的一些說明:
1) SWFUpload使用一個隱藏的Flash影片來控制文件的選擇和上傳。
2) JavaScript用來激活文件選擇對話框。此文件選擇對話框是可以設置允許用戶選擇一個單獨的文件或者是多個文件。 選擇的的文件類型也是可以被限制的,因此用戶只能選擇指定的適當的文件,例如*.jgp;*.gif。
3) 當選定文件以後,每個文件都會被驗證和處理。當Flash上傳文件的時候,由開發人員預定義的Javascript事件會被定時觸發以便來更新頁面中的UI,同時還提供上傳狀態和錯誤信息。
4) 選定的文件的上傳和它所在頁面、表單是獨立的。每個文件都是單獨上傳的,這就保證了服務端腳本能夠在一個時間點更容易地處理單個文件。雖然Flash提供了上傳服務,但是頁面並不會提交或者重新載入。相比於標準的HTML Form,SWFUpload的使用方式更像是AJAX程序,頁面中的Form會和FLASH控制的文件上傳單獨處理。
具體信息可以訪問swfupload官方網站:http://www.swfupload.org/
讓我們先來看看客戶端的界面效果圖。(多選文件,批量上傳,上傳進度顯示)
1) 進行多文件選擇:
圖1
2) 上傳進度顯示
圖2
下面進行具體的操作:
第一步,要進行下面的過程,必須先準備好Flash插件和SwfUpload組件。
1) Flash插件:相信大家的瀏覽器早已經安裝過了,請檢查版本,儘量使用最新的的flash插件。
2) SwfUpload:大家可以訪問swfupload官方網站:http://www.swfupload.org/,在這個網站上可以下載到組件與demo。
第二步,創建應用的目錄結構,我這個示例的目錄結構如圖:
1.主要目錄結構
2. 文件上傳用到的js腳本文件。
3. swfupload目錄中的文件
第三步,前臺部分準備客戶操作的WEB界面,如下[TestUploadFile2.aspx、uploadFile.aspx]
1) 前臺客戶端代碼,其中TestUploadFile2.aspx的代碼如下,TestUploadFile2.aspx.cs文件中只使用默認的代碼,不用添加任何代碼。
TestUploadFile2.aspx
Html代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestUploadFile2.aspx.cs" Inherits="TestUploadFile2" %>
<!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>
<link href="css/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="swfupload/swfupload.js"></script>
<script type="text/javascript" src="simpledemo/js/swfupload.queue.js"></script>
<script type="text/javascript" src="simpledemo/js/fileprogress.js"></script>
<script type="text/javascript" src="simpledemo/js/handlers.js"></script>
<script type="text/javascript">
var swfu;
window.onload = function() {
var settings = {
flash_url : "../swfupload/swfupload.swf",
upload_url: "uploadFile.aspx",
post_params: {
"ASPSESSID": "<%=Session.SessionID %>"
},
file_size_limit : "100 MB",
file_types : "*.*", //這是全部文件都可以上傳,如果要限制只有某些文件上傳,則可以這麼寫 file_types : "*.jpg;*.gif;*.png",
file_types_description : "All Files",
file_upload_limit : 100,
file_queue_limit : 0,
custom_settings : {
progressTarget : "fsUploadProgress",
cancelButtonId : "btnCancel"
},
debug: false,
// Button settings
//這兒是swfupload v2新增加的功能,由於flash player 10的安全性的提高所以增加了此功能。
//在SWFUpload v2中,不能再使用html的button來觸發SWFUpload,必須使用定製的Button,這其中比較要注意的是,button不能再用css控制,需要用圖片來顯示
button_image_url: "images/XPButtonNoText_160x22.png",
button_placeholder_id: "spanButtonPlaceholder",
button_width: 160,
button_height: 22,
button_text: '<span class="button"> 選擇文件 <span class="buttonSmall">(2 MB Max)</span></span>',
button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
button_text_top_padding: 1,
button_text_left_padding: 5,
// The event handler functions are defined in handlers.js
file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_start_handler : uploadStart,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
queue_complete_handler : queueComplete // Queue plugin event
};
swfu = new SWFUpload(settings);
};
</script>
</head>
<body>
<div id="content">
<h2>一次選擇多個文件進行上傳</h2>
<form id="form1" runat="Server">
<div>
<span id="spanButtonPlaceHolder"></span>
<input id="btnCancel" type="button" value="取消全部上傳" οnclick="swfu.cancelQueue();" disabled="disabled" style="margin-left: 2px; font-size: 8pt; height: 22px;" />
</div>
<p> </p>
<div class="fieldset flash" id="fsUploadProgress">
<span class="legend">Upload Queue</span>
</div>
<div id="divStatus">0 個文件已經上傳</div>
</form>
</div>
</body>
</html>
以上代碼最後的顯示結果如圖:
圖3.
2)後臺服務器端代碼:uploadFile.aspx文件中使用默認的代碼,不需要添加任何代碼。uploadFile.aspx.cs文件的代碼如下:
uploadFile.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class net_uploadFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.CacheControl = "no-cache";
string s_rpath =@"E:\WebSites\SWFUpload\demos\applicationdemo.net\";
string Datedir = DateTime.Now.ToString("yy-MM-dd");
string updir = s_rpath + "\\" + Datedir;
if (this.Page.Request.Files.Count > 0)
{
try
{
for (int j = 0; j < this.Page.Request.Files.Count; j++)
{
HttpPostedFile uploadFile = this.Page.Request.Files[j];
if (uploadFile.ContentLength > 0)
{
if (!Directory.Exists(updir))
{
Directory.CreateDirectory(updir);
}
string extname = Path.GetExtension(uploadFile.FileName);
string 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();
string filename = uploadFile.FileName;
uploadFile.SaveAs(string.Format("{0}\\{1}", updir, filename));
}
}
}
catch (Exception ex)
{
Response.Write("Message"+ ex.ToString());
}
}
}
}
第四步,如果使用以上代碼,在具體的應用中不能使用或是ie可行,ff不行,則需要在Global.asax文件中添加以下代碼。
如果Global.asax文件不存在,則請在應用的根目錄中創建。
<%@ Application Language="C#" %>
<script runat="server">
void Application_BeginRequest(object sender, EventArgs e)
{
/* Fix for the Flash Player Cookie bug in Non-IE browsers.
* Since Flash Player always sends the IE cookies even in FireFox
* we have to bypass the cookies by sending the values as part of the POST or GET
* and overwrite the cookies with the passed in values.
*
* The theory is that at this point (BeginRequest) the cookies have not been read by
* the Session and Authentication logic and if we update the cookies here we'll get our
* Session and Authentication restored correctly
*/
try
{
string session_param_name = "ASPSESSID";
string session_cookie_name = "ASP.NET_SESSIONID";
if (HttpContext.Current.Request.Form[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
}
else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
}
}
catch (Exception)
{
Response.StatusCode = 500;
Response.Write("Error Initializing Session");
}
try
{
string auth_param_name = "AUTHID";
string auth_cookie_name = FormsAuthentication.FormsCookieName;
if (HttpContext.Current.Request.Form[auth_param_name] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
}
else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
}
}
catch (Exception)
{
Response.StatusCode = 500;
Response.Write("Error Initializing Forms Authentication");
}
}
void UpdateCookie(string cookie_name, string cookie_value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
if (cookie == null)
{
cookie = new HttpCookie(cookie_name);
HttpContext.Current.Request.Cookies.Add(cookie);
}
cookie.Value = cookie_value;
HttpContext.Current.Request.Cookies.Set(cookie);
}
</script>
第五步,在進行上傳之後的結果如圖:
最後的關於swfupload v2版的一些說明:
void selectFile()
不贊成使用,不兼容Flash Player 10
彈出flash的文件選擇對話框,只能選擇單個文件。
void selectFiles()
不贊成使用,不兼容Flash Player 10
彈出flash的文件選擇對話框,可一次性選擇多個文件。
flash_url : "../swfupload/swfupload.swf",
這句話改成 flash_url : "swfupload/swfupload.swf",
就可以看到選擇文件的按鈕了,