asp.net(c#)開發中的檔案上傳組件uploadify的使用方法(帶進度條)

來源:互聯網
上載者:User

在Web開發中,有很多可以上傳的組件模組,利用HTML的File控制項的上傳也是一種辦法,不過這種方式,需要處理的細節比較多,而且只能支援單檔案的操作。在目前Web開發中用的比較多的,可能uploadify(參考http://www.uploadify.com/)也算一個吧,不過這個版本一直在變化,他們的指令碼調用也有很大的不同,甚至調用及參數都一直在變化,很早的時候,那個Flash的按鈕文字還沒法變化,本篇隨筆主要根據項目實際,介紹一下3.1版本的uploadify的控制項使用,這版本目前還是最新的,因此對我們做Web開發來說,有一定的參考性。

這個控制項有很多參數控制,以及事件的處理響應,相對來說也比較好用。參數控制可以控制上傳檔案多選、檔案類型、檔案大小、檔案數量、檢查檔案是否存在,以及一些按鈕參數的控制,如文字、高度、寬度等,對提交檔案成功與否、完成操作、取消、停止上傳等等都有控制,他們的協助文檔也寫得比較完善,不過就是各個版本的方法參數完全不同了,但控制項是一個好控制項。

控制項的使用首先要加入必備的指令碼類庫,由於該控制項是利用了Jquery的功能,因此還需要應用Jquery指令檔,如下所示。

複製代碼 代碼如下: <script src="http://www.jb51.net/JQuery/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="http://www.jb51.net/JQueryTools/uploadify/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
<link href="http://www.jb51.net/JQueryTools/uploadify/uploadify.css" rel="stylesheet" type="text/css" />

配置控制項的一些參數,以及相應的處理事件,如下所示。

複製代碼 代碼如下:<script language="javascript" type="text/javascript">
$(function () {
var guid = '<%=Request["guid"] %>';
var type = '<%=Request["type"] %>';
if (guid == null || guid == "") {
guid = newGuid();
}
if (type != null) {
type = type + '/';
}

$('#file_upload').uploadify({
'swf': 'uploadify.swf', //FLash檔案路徑
'buttonText': '瀏 覽', //按鈕文本
'uploader': 'uploadhandler.ashx?guid=' + guid, //處理ASHX頁面
'formData' : { 'folder' : 'picture' }, //傳參數
'queueID': 'fileQueue', //隊列的ID
'queueSizeLimit': 10, //隊列最多可上傳檔案數量,預設為999
'auto': false, //選擇檔案後是否自動上傳,預設為true
'multi': true, //是否為多選,預設為true
'removeCompleted': true, //是否完成後移除序列,預設為true
'fileSizeLimit': '10MB', //單個檔案大小,0為無限制,可接受KB,MB,GB等單位的字串值
'fileTypeDesc': 'Image Files', //檔案描述
'fileTypeExts': '*.gif; *.jpg; *.png; *.bmp', //上傳的檔案尾碼過濾器
'onQueueComplete': function (event, data) { //所有隊列完成後事件
//ShowUpFiles(guid, type, show_div);
alert("上傳完畢!");
},
'onUploadError': function (event, queueId, fileObj, errorObj) {
alert(errorObj.type + ":" + errorObj.info);
}
});
});

function newGuid() {
var guid = "";
for (var i = 1; i <= 32; i++){
var n = Math.floor(Math.random()*16.0).toString(16);
guid += n;
if((i==8)||(i==12)||(i==16)||(i==20))
guid += "-";
}
return guid;
}
</script>

再次提一下,這個控制項不要參考網上其他的一些說明,否則可能參數及用法不正確,一定要找到對應版本的說明(本篇指的是3.1.1),最好參考該版本的線上文檔。

上面的參數,我基本上都給了注釋了,還有一些不是很重要的參數,這裡沒有列出來,需要可以參考線上文檔吧。

值得提到的是,這個版本可以修改Flash裡面的文字,非常棒,很討厭以前的那個預設Browse的英文,雖然以前替代圖片可以修改文字,但是還是不太好用。這個直接修改文字,非常好。

值得注意的是uploader參數,這個是我們ashx的幕後處理程式,就是控制項提交檔案給那個頁面進行儲存處理,添加資料庫記錄等操作。

頁面代碼使用很簡單,如下所示

複製代碼 代碼如下:<body style="margin-left:10px; margin-top:10px">
<form id="form1" runat="server" enctype="multipart/form-data">
<div id="fileQueue" class="fileQueue"></div>

<div>
<input type="file" name="file_upload" id="file_upload" />
<p>
<input type="button" class="shortbutton" id="btnUpload" onclick="javascript:$('#file_upload').uploadify('upload','*')" value="上傳" />

<input type="button" class="shortbutton" id="btnCancelUpload" onclick="javascript:$('#file_upload').uploadify('cancel')" value="取消" />
</p>
<div id="div_show_files"></div>
</div>
</form>
</body>

關鍵是後台上傳檔案的儲存操作了,asp.net一般採用ashx的處理頁面來處理。複製代碼 代碼如下:/// <summary>
/// 檔案上傳幕後處理頁面
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class UploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";

try
{
string guid = context.Request.QueryString["guid"];
string folder = context.Request["folder"];
//LogTextHelper.Info(folder);

HttpPostedFile file = context.Request.Files["Filedata"];
if (file != null)
{
string oldFileName = file.FileName;//原檔案名稱
int size = file.ContentLength;//附件大小

string extenstion = oldFileName.Substring(oldFileName.LastIndexOf(".") + 1);//尾碼名
string newFileName = GetNewFileName(oldFileName);//產生新檔案名稱
//LogTextHelper.Info(newFileName);

#region 上傳到遠程伺服器
//FileServerManage fsw = new FileServerManage();
//string uploadFilePath = "/" + newFileName;
//if (!string.IsNullOrEmpty(folder))
//{
// uploadFilePath = string.Format("/{0}/{1}", folder, newFileName);
//}
//bool uploaded = fsw.UploadFile(file.InputStream, "/" + folder + "/" + newFileName);
#endregion

#region 本機伺服器上傳

AppConfig config = new AppConfig();
string uploadFiles = config.AppConfigGet("uploadFiles");
if (string.IsNullOrEmpty(uploadFiles))
{
uploadFiles = "uploadFiles";
}
if (!string.IsNullOrEmpty(folder))
{
uploadFiles = Path.Combine(uploadFiles, folder);
}

string uploadPath = Path.Combine(HttpContext.Current.Server.MapPath("/"), uploadFiles);
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
string newFilePath = Path.Combine(uploadPath, newFileName);
LogTextHelper.Info(newFilePath);
file.SaveAs(newFilePath);
bool uploaded = File.Exists(newFilePath);

#endregion

if (uploaded)
{
#region 檔案儲存成功後,寫入附件的資料庫記錄
//AttachmentInfo attachmentInfo = new AttachmentInfo();
//attachmentInfo.EditorTime = DateTime.Now;
//attachmentInfo.FileExtend = extenstion;
//attachmentInfo.FileName = folader + "/" + newFileName;
//attachmentInfo.OldFileName = oldFileName;
//attachmentInfo.Size = size;
//attachmentInfo.Guid = guid;
//BLLFactory<Attachment>.Instance.Insert(attachmentInfo);
#endregion
}
}
else
{
LogTextHelper.Error("上傳檔案失敗");
}
}
catch (Exception ex)
{
LogTextHelper.Error("上傳檔案失敗", ex);
throw;
}
}

/// <summary>
/// 擷取新的名稱 比如:aa.jpg轉化為aa(20090504).jpg
/// </summary>
/// <param name="fileName">檔案名稱[aa.jpg]</param>
/// <returns>新的檔案名稱</returns>
public static string GetNewFileName(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return string.Empty;

//檔案尾碼名
string extenstion = fileName.Substring(fileName.LastIndexOf(".") + 1);
string name = fileName.Substring(0, fileName.LastIndexOf(".")) + "(" + DateTime.Now.ToFileTime() + ")";
string newFileName = name + "." + extenstion;
return newFileName;
}

public bool IsReusable
{
get
{
return false;
}
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.