1. 程式人生 > >jQuery上傳插件Uploadify 3.2在.NET下的詳細例子

jQuery上傳插件Uploadify 3.2在.NET下的詳細例子

formdata 高度 jpg javascrip summary ride ocl ready onclick

項目中要使用Uploadify 3.2來實現圖片上傳並生成縮略通的功能,特此記下來,以供各位參考!

Uploadify下載地址:http://www.uploadify.com/download/

下載下來解壓後估計裏面很多文件,其實有用的也就jQuery.uploadify.min.js、uploadify.css、uploadify.swf和uploadify-cancel.png這四個文件。你還得下載jquery庫,我這裏用的是jquery-1.7.2.min.js,另外和大多數JQ插件一樣,同時也需要swfobject.js這個插件,我的是2.2的版本,東西都準備好了,那下面就開始。

前端界面:

[html] view plain copy
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jqUploadify._Default" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title>無標題頁</title>
  6. <link href="scripts/uploadify.css" rel="stylesheet" type="text/css" />
  7. <link href="scripts/default.css" rel="stylesheet" type="text/css" />
  8. <script src="scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
  9. <script src="scripts/swfobject.js" type="text/javascript"></script>
  10. <script src="scripts/jquery.uploadify.min.js" type="text/javascript"></script>
  11. <script type="text/javascript">
  12. $(function(){
  13. $("#file_upload").uploadify({
  14. //開啟調試
  15. ‘debug‘ : false,
  16. //是否自動上傳
  17. ‘auto‘:false,
  18. ‘buttonText‘:‘選擇照片‘,
  19. //flash
  20. ‘swf‘: "scripts/uploadify.swf",
  21. //文件選擇後的容器ID
  22. ‘queueID‘:‘uploadfileQueue‘,
  23. ‘uploader‘:‘scripts/upload.ashx‘,
  24. ‘width‘:‘75‘,
  25. ‘height‘:‘24‘,
  26. ‘multi‘:false,
  27. ‘fileTypeDesc‘:‘支持的格式:‘,
  28. ‘fileTypeExts‘:‘*.jpg;*.jpge;*.gif;*.png‘,
  29. ‘fileSizeLimit‘:‘1MB‘,
  30. ‘removeTimeout‘:1,
  31. //返回一個錯誤,選擇文件的時候觸發
  32. ‘onSelectError‘:function(file, errorCode, errorMsg){
  33. switch(errorCode) {
  34. case -100:
  35. alert("上傳的文件數量已經超出系統限制的"+$(‘#file_upload‘).uploadify(‘settings‘,‘queueSizeLimit‘)+"個文件!");
  36. break;
  37. case -110:
  38. alert("文件 ["+file.name+"] 大小超出系統限制的"+$(‘#file_upload‘).uploadify(‘settings‘,‘fileSizeLimit‘)+"大小!");
  39. break;
  40. case -120:
  41. alert("文件 ["+file.name+"] 大小異常!");
  42. break;
  43. case -130:
  44. alert("文件 ["+file.name+"] 類型不正確!");
  45. break;
  46. }
  47. },
  48. //檢測FLASH失敗調用
  49. ‘onFallback‘:function(){
  50. alert("您未安裝FLASH控件,無法上傳圖片!請安裝FLASH控件後再試。");
  51. },
  52. //上傳到服務器,服務器返回相應信息到data裏
  53. ‘onUploadSuccess‘:function(file, data, response){
  54. //alert(data);
  55. }
  56. });
  57. });
  58. function doUplaod(){
  59. $(‘#file_upload‘).uploadify(‘upload‘,‘*‘);
  60. }
  61. function closeLoad(){
  62. $(‘#file_upload‘).uploadify(‘cancel‘,‘*‘);
  63. }
  64. </script>
  65. </head>
  66. <body>
  67. <table width="704" border="0" align="center" cellpadding="0" cellspacing="0" id="__01">
  68. <tr>
  69. <td align="center" valign="middle">
  70. <div id="uploadfileQueue" style="padding: 3px;">
  71. </div>
  72. <div id="file_upload">
  73. </div>
  74. </td>
  75. </tr>
  76. <tr>
  77. <td height="50" align="center" valign="middle">
  78. <img alt="" src="images/BeginUpload.gif" width="77" height="23" onclick="doUplaod()" style="cursor: hand" />
  79. <img alt="" src="images/CancelUpload.gif" width="77" height="23" onclick="closeLoad()" style="cursor: hand" />
  80. </td>
  81. </tr>
  82. </table>
  83. </body>
  84. </html>

後端的Handler:

[csharp] view plain copy
  1. using System;
  2. using System.Collections;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Services;
  7. using System.Web.Services.Protocols;
  8. using System.Xml.Linq;
  9. using System.Web.SessionState;
  10. using System.IO;
  11. namespace jqUploadify.scripts
  12. {
  13. /// <summary>
  14. /// $codebehindclassname$ 的摘要說明
  15. /// </summary>
  16. [WebService(Namespace = "http://tempuri.org/")]
  17. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  18. public class upload : IHttpHandler, IRequiresSessionState
  19. {
  20. public void ProcessRequest(HttpContext context)
  21. {
  22. context.Response.ContentType = "text/plain";
  23. context.Response.Charset = "utf-8";
  24. HttpPostedFile file = context.Request.Files["Filedata"];
  25. string uploadPath = context.Server.MapPath("..\\uploads\\");
  26. if (file != null)
  27. {
  28. if (!Directory.Exists(uploadPath))
  29. {
  30. Directory.CreateDirectory(uploadPath);
  31. }
  32. file.SaveAs(uploadPath + file.FileName);
  33. //生成縮略圖
  34. MakeThumbnail(uploadPath + file.FileName, uploadPath + "\\s\\" + file.FileName, 80, 80);
  35. }
  36. }
  37. private void MakeThumbnail(string sourcePath, string newPath, int width, int height)
  38. {
  39. System.Drawing.Image ig = System.Drawing.Image.FromFile(sourcePath);
  40. int towidth = width;
  41. int toheight = height;
  42. int x = 0;
  43. int y = 0;
  44. int ow = ig.Width;
  45. int oh = ig.Height;
  46. if ((double)ig.Width / (double)ig.Height > (double)towidth / (double)toheight)
  47. {
  48. oh = ig.Height;
  49. ow = ig.Height * towidth / toheight;
  50. y = 0;
  51. x = (ig.Width - ow) / 2;
  52. }
  53. else
  54. {
  55. ow = ig.Width;
  56. oh = ig.Width * height / towidth;
  57. x = 0;
  58. y = (ig.Height - oh) / 2;
  59. }
  60. System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
  61. System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
  62. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
  63. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  64. g.Clear(System.Drawing.Color.Transparent);
  65. g.DrawImage(ig, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
  66. try
  67. {
  68. bitmap.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg);
  69. }
  70. catch (Exception ex)
  71. {
  72. throw ex;
  73. }
  74. finally
  75. {
  76. ig.Dispose();
  77. bitmap.Dispose();
  78. g.Dispose();
  79. }
  80. }
  81. public bool IsReusable
  82. {
  83. get
  84. {
  85. return false;
  86. }
  87. }
  88. }
  89. }

這樣我們就是實現圖片上傳至uploads,生成的縮略圖(這裏設為80*80)存放在uploads下面的s文件夾中,是不是很簡單呢!當然實際使用過程你還可能碰到一下的問題:

1、在火狐下session出現丟失的情況,可以參考這裏:http://www.cnblogs.com/akingyao/archive/2012/09/04/2670794.html

2、IE9出現了按鈕不能點擊的問題,可以參考這裏:http://www.uploadify.com/forum/#/discussion/9155/uploadify-version-3-2-does-not-work-in-ie9/p1

最後貼一個Uploadify參數說明:

Uploadify Version 3.2

Options選項設置


auto 選擇文件後自動上傳
buttonClass 給“瀏覽按鈕”加css的class樣式
buttonCursor 鼠標移上去形狀:arrow箭頭、hand手型(默認)
buttonImage 鼠標移上去變換圖片
buttonText 按鈕文字
checkExisting 在目錄中檢查文件是否已上傳成功(1 ture,0 false)
debug 是否顯示調試框(默認不顯示false)
fileObjName 設置一個名字,在服務器處理程序中根據該名字來取上傳文件的數據。默認為Filedata,$tempFile = $_FILES[‘Filedata‘][‘tmp_name‘]
fileSizeLimit 設置允許上傳文件最大值B, KB, MB, GB 比如:‘fileSizeLimit‘ : ‘20MB‘
fileTypeDesc 選擇的文件的描述。這個字符串出現在瀏覽文件對話框中文件類型下拉框處。默認:All Files
fileTypeExts 允許上傳的文件類型。格式:‘fileTypeExts‘ : ‘*.gif; *.jpg; *.png‘
formData 附帶值,需要通過get or post傳遞的額外數據,需要結合onUploadStart事件一起使用
height “瀏覽按鈕”高度px
itemTemplate <itemTemplate>節點表示顯示的內容。這些內容中也可以包含綁定到控件DataSource屬性中元素集合的數據。
method 上傳方式。默認:post
multi 選擇文件時是否可以【選擇多個】。默認:可以true
overrideEvents 不執行默認的onSelect事件
preventCaching 隨機緩存值 默認true ,可選true和false.如果選true,那麽在上傳時會加入一個隨機數來使每次的URL都不同,以防止緩存.但是可能與正常URL產生沖突
progressData 進度條上顯示的進度:有百分比percentage和速度speed。默認百分比
queueID 給“進度條”加背景css的ID樣式。文件選擇後的容器ID
queueSizeLimit 允許多文件上傳的數量。默認:999
removeCompleted 上傳完成後隊列是否自動消失。默認:true
removeTimeout 上傳完成後隊列多長時間後消失。默認 3秒 需要:‘removeCompleted‘ : true,時使用
requeueErrors 隊列上傳出錯,是否繼續回滾隊列,即反復嘗試上傳。默認:false
successTimeout 上傳超時時間。文件上傳完成後,等待服務器返回信息的時間(秒).超過時間沒有返回的話,插件認為返回了成功。 默認:30秒
swf swf文件的路徑,本文件是插件自帶的,不可用其它的代替.本參數不可省略
uploader 上傳處理程序URL,本參數不可省略
uploadLimit 限制總上傳文件數,默認是999。指同一時間,如果關閉瀏覽器後重新打開又可上傳。
width “瀏覽按鈕”寬度px

Events 事件
onCancel 當取消一個上傳隊列中的文件時觸發,刪除時觸發
onClearQueue 清除隊列。當‘cancel‘方法帶著*參數時,也就是說一次全部取消的時候觸發.queueItemCount是被取消的文件個數(另外的按鈕)
onDestroy 取消所有的上傳隊列(另外的按鈕)
onDialogClose 當選擇文件對話框關閉時觸發,不論是點的‘確定‘還是‘取消‘都會觸發.如果本事件被添加進了‘overrideEvents‘參數中,那麽如果在選擇文件時產生了錯誤,不會有錯誤提示框彈出
onDialogOpen 當選擇文件框被打開時觸發,沒有傳過來的參數
onDisable 關閉上傳
onEnable 開啟上傳
onFallback 檢測FLASH失敗調用
onInit 每次初始化一個隊列時觸發
onQueueComplete 當隊列中的所有文件上傳完成時觸發
onSelect 當文件從瀏覽框被添加到隊列中時觸發
onSelectError 選擇文件出錯時觸發
onSWFReady flash準備好時觸發
onUploadComplete當一個文件上傳完成時觸發
onUploadError 當文件上傳完成但是返回錯誤時觸發
onUploadProgress上傳匯總
onUploadStart 一個文件上傳之間觸發
onUploadSuccess 每個上傳完成並成功的文件都會觸發本事件

Methods 方法
cancel 取消一個上傳隊列
destroy 取消所有上傳隊列
disable 禁止點擊“瀏覽按鈕”
settings 返回或修改一個 uploadify實例的settings值
stop 停止當前的上傳並重新添加到隊列中去
upload 上傳指定的文件或者所有隊列中的文件

最後是DEMO的下載地址:http://download.csdn.net/detail/wangqiuyun/5665517

jQuery上傳插件Uploadify 3.2在.NET下的詳細例子