ASP.NET檔案上傳控制項Uploadify的使用方法_實用技巧

來源:互聯網
上載者:User

對於檔案上傳來說,有很多種實現方式,如傳統的表單方式,現在流行的flash方式,甚至還有純JS方式,之所以有這些方式來實現檔案上傳,我想主要原因是因為,傳統的上傳對於大檔案支援不夠,因為它是單線程同步機制,當大檔案通過HTTP方式發送到服務端時,對於服務端網站的主線程影響比較大,會產生阻塞,所以,現在很多上傳控制都是非同步,多線程的方式去實現的.

今天來介紹一個檔案上傳控制,它就是Uploadify,它應該是flash的非同步上傳工具,對於大檔案支援還不錯,所以,我選擇了它.

相關API介紹

uploader : uploadify.swf 檔案的相對路徑,該swf檔案是一個帶有文字BROWSE的按鈕,點擊後淡出開啟檔案對話方塊,預設值:uploadify.swf。
script :   幕後處理程式的相對路徑 。預設值:uploadify.php
checkScript :用來判斷上傳選擇的檔案在伺服器是否存在的幕後處理程式的相對路徑
fileDataName :設定一個名字,在伺服器處理常式中根據該名字來取上傳檔案的資料。預設為Filedata
method : 提交方式Post 或Get 預設為Post
scriptAccess :flash指令檔的訪問模式,如果在本地測試設定為always,預設值:sameDomain 
folder :  上傳檔案存放的目錄 。
queueID : 檔案隊列的ID,該ID與存放檔案隊列的div的ID一致。
queueSizeLimit : 當允許多檔案產生時,設定選擇檔案的個數,預設值:999 。
multi : 設定為true時可以上傳多個檔案。
auto : 設定為true當選擇檔案後就直接上傳了,為false需要點擊上傳按鈕才上傳 。

fileExt : 設定可以選擇的檔案的類型,格式如:'*.jpg;*.gif,*.png' 。

fileDesc : 這個屬性值必須設定fileExt屬性後才有效,用來設定選擇檔案對話方塊中的提示文本,如設定fileDesc為“請選擇影像檔”,
sizeLimit : 上傳檔案的大小限制 。
simUploadLimit : 允許同時上傳的個數 預設值:1 。
buttonText : 瀏覽按鈕的文本,預設值:BROWSE 。
buttonImg : 瀏覽按鈕的圖片的路徑 。
hideButton : 設定為true則隱藏瀏覽按鈕的圖片 。
rollover : 值為true和false,設定為true時當滑鼠移到瀏覽按鈕上時有反轉效果。
width : 設定瀏覽按鈕的寬度 ,預設值:110。
height : 設定瀏覽按鈕的高度 ,預設值:30。
wmode : 設定該項為transparent 可以使瀏覽按鈕的flash背景檔案透明,並且flash檔案會被置為頁面的最高層。 預設值:opaque 。
cancelImg :選擇檔案到檔案隊列中後的每一個檔案上的關閉按鈕表徵圖

結構圖

HTML代碼

<div> <div class="inputDiv fl"> <input type="text" name="ImagePath" id="ImagePath" style="width: 600px;"> <img style="display: none;" /> </div> <div class="fl" style="position: relative;"> <input id="custom_file_uploadEdu" type="file" class="btn" /> <a href="javascript:$('#custom_file_uploadEdu').uploadifyUpload()">上傳</a>|  <a href="javascript:$('#custom_file_uploadEdu').uploadifyClearQueue()">取消上傳</a> </div> <div id="displayMsg"></div></div>

JS代碼

<script type="text/ecmascript"> $("#custom_file_uploadEdu").uploadify({ 'uploader': '/Scripts/Uploadify/uploadify.swf', 'script': '/ashx/UploadFile.ashx', 'cancelImg': '/Scripts/Uploadify/uploadify-cancel.png', 'folder': '/', 'queueSizeLimit': 1, 'simUploadLimit': 1, 'sizeLimit ': 1024 * 1024 * 5, 'multi': false, 'auto': false,/*如果是自動上傳,那上傳按鈕將沒用了*/ 'fileExt': '*.jpg;*.gif;*.jpeg;*.mp4', 'fileDesc': '請選擇映像或者視頻', 'queueID': 'fileQueue', 'width': 110, 'height': 30, 'buttonText': '選擇', 'wmode': 'opaque', 'hideButton': false, 'onSelect': function (event, ID, fileObj) {  $("#displayMsg").html("上傳中......"); }, 'onComplete': function (event, queueId, fileObj, response, data) {  var ary = response.split('|');  if (ary[0] == "0") { //提示錯誤資訊  alert(ary[1]);  }  else {  if (ary[0]=="1") {//上傳後的URL   $("#displayMsg").html("上傳成功")   $("#ImagePath").attr("value", ary[1]);   $("#ImagePath").remove("img").next("img").show().attr({ "style": "width:50px;height:50px;", "src": ary[1] });  } else {//異常資訊   alert(ary[1]);  }  } } });</script>

幕後處理程式(接收流,寫入流)

namespace WebTest.ashx{ /// <summary> /// UploadFile 的摘要說明 /// </summary> public class UploadFile : IHttpHandler { public void ProcessRequest(HttpContext context) {  context.Response.ContentType = "text/plain";  context.Response.Write(new UploadImpl().Upload(context, UpLoadType.ProductImage, false)); } public bool IsReusable {  get  {  return false;  } } }}

UploadImpl類代碼

namespace EntityFrameworks.Application.Core.FileUpload{ /// <summary> /// 映像上傳功能的實現 /// </summary> public class UploadImpl { public UploadImpl(IFileUploadSize fileUploadSize) {  _fileUploadSize = fileUploadSize ?? new TestFileUploadSize(); } public UploadImpl()  : this(null) { } #region Fields & Consts static string FileHostUri = System.Configuration.ConfigurationManager.AppSettings["FileHostUri"]  ?? HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority; Point point = new Point(0, 0); //映像從那個座標點進行截取 double wRate = 1, hRate = 1, setRate = 1; int newWidth = 0, newHeight = 0; IFileUploadSize _fileUploadSize; #endregion #region 映像縮放 /// <summary> /// 映像的縮放 /// </summary> /// <param name="file">縮放檔案</param> /// <param name="width">寬</param> /// <param name="height">高</param> /// <param name="isEqualScale">是否等比例縮放</param> /// <param name="name">縮放後存放的地址</param> /// <returns></returns> bool CreateThumbnail(HttpPostedFile file, ImageSize imageSize, bool isEqualScale, string name) {  double width = (double)imageSize.Width;  double height = (double)imageSize.Height; ;  try  {  System.Drawing.Image image = System.Drawing.Image.FromStream(file.InputStream);  if (isEqualScale)  {   if (image.Height > height)   {   hRate = height / image.Height;   }   if (image.Width > width)   {   wRate = width / image.Width;   }   if (wRate != 1 || hRate != 1)   {   if (wRate > hRate)   {    setRate = hRate;   }   else   {    setRate = wRate;   }   }   newWidth = (int)(image.Width * setRate);   newHeight = (int)(image.Height * setRate);   if (height > newHeight)   {   point.Y = Convert.ToInt32(height / 2 - newHeight / 2);   }   if (width > newWidth)   {   point.X = Convert.ToInt32(width / 2 - newWidth / 2);   }  }  Bitmap bit = new Bitmap((int)(width), (int)(height));  Rectangle r = new Rectangle(point.X, point.Y, (int)(image.Width * setRate), (int)(image.Height * setRate));  Graphics g = Graphics.FromImage(bit);  g.Clear(Color.White);  g.DrawImage(image, r);  MemoryStream ms = new MemoryStream();  bit.Save(ms, ImageFormat.Jpeg);  byte[] bytes = ms.ToArray();  string fileName = name + imageSize.ToString();//為縮放映像重新命名  using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))  {   stream.Write(bytes, 0, bytes.Length);  }  bit.Dispose();  ms.Dispose();  image.Dispose();  return true;  }  catch (Exception)  {  return false;  } } /// <summary> /// 映像的等比例縮放,預設檔案名稱不改變,會將原檔案覆蓋 /// </summary> /// <param name="file"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> bool CreateThumbnail(HttpPostedFile file, ImageSize imageSize, string name) {  return CreateThumbnail(file, imageSize, true, name); } #endregion public string Upload(HttpContext context, UpLoadType type, bool isScale) {  ImageSize imageSize = _fileUploadSize.ImageSizeForType[type];  HttpFileCollection files = context.Request.Files;  if (files.Count == 0)  {  throw new ArgumentNullException("please choose file for upload.");  }  string path = "/upload/" + type.ToString();//相對路徑  if (!Directory.Exists(path))  Directory.CreateDirectory(path);  // 只取第 1 個檔案  var file = files[0];  if (file != null && file.ContentLength > 0)  {  try  {   string filename = context.Request.Form["fileName"].Split('.')[0]   + "_"   + DateTime.Now.ToString("yyyyMMddhhssmm")   + imageSize.ToString();   // 本地檔案系統路徑   string savePath = Path.Combine(context.Server.MapPath(path), filename);   file.SaveAs(savePath);   if (isScale)   CreateThumbnail(file, imageSize, savePath);   //返回URI路徑   string ImageUri = FileHostUri   + path   + "/"   + filename;   return "1|" + ImageUri;  }  catch (Exception ex)  {   return "0|" + ex.Message;  }  }  return null; } }}

效果圖:

為大家推薦一個專題,供大家學習:《ASP.NET檔案上傳匯總》

以上就是關於ASP.NET檔案上傳控制項Uploadify的第一部分內容介紹,接下來還有更新,希望大家不要錯過。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.