程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> 使用SWFUpload實現無刷新上傳圖片

使用SWFUpload實現無刷新上傳圖片

編輯:ASP.NET基礎

在做項目時,需要用到一個圖片的無刷新上傳,之前聽說過SWFUpload,於是想要通過SWFUpload來進行圖片的無刷新上傳,由於我的項目屬於是ASP.NET項目,所以本文著重講解ASP.NET 的使用,個人感覺示例基本給的很清晰,參考文檔進行開發,並非難事

0. 首先下載swfUpload 包,在下載的包中有samples文件夾,samples下有demos文件夾,打開demos文件夾可看到如下圖所示結構

我們待會會用到的包括,swfupload目錄下的文件,css不建議使用以避免與自己寫的CSS相沖突使得頁面布局完全亂掉,如果要添加樣式最好自己寫

打開 applicationdemo.net目錄會看到這樣的結構

打開index.html可以看到這樣的頁面

點擊NET2.0下的Application Demo C#項

添加資源引用

將要引用的資源包含到項目中(包括swfupload文件夾下的文件與,demo下的資源文件,handlers.js是在demo中js目錄下的js文件)

首先熟悉demo,將demo中的頁面包含到項目中

在Defaut.aspx頁面中使用swfUpload組件進行圖片的無刷新上傳直接運行,看效果,大概了解基本過程

修改handlers.js文件

我的項目文件結構大概是這樣的

我的處理文件上傳的頁面是ImageUploadHandler.ashx,獲取縮略圖的頁面是GetThumbHandler.ashx,Thumbnail.cs是demo中App_Code文件夾中的文件,個人覺得像這種只處理邏輯功能而不展現頁面的最好都用一般處理程序來實現。由於哪個文件處理上傳哪個文件生成縮略圖已經在handlers.js文件中寫死了,所以必須要修改handlers.js文件以能夠使頁面正常運行

最終修改版匯總

Thumbnail

/// <summary>
/// 縮略圖
/// </summary>
public class Thumbnail
{
  public Thumbnail(string id, byte[] data)
  {
    this.ID = id;
    this.Data = data;
  }

  private string id;

  /// <summary>
  /// 圖片id
  /// </summary>
  public string ID
  {
    get
    {
      return this.id;
    }
    set
    {
      this.id = value;
    }
  }

  private byte[] thumbnail_data;

  /// <summary>
  /// 圖片的二進制數據
  /// </summary>
  public byte[] Data
  {
    get
    {
      return this.thumbnail_data;
    }
    set
    {
      this.thumbnail_data = value;
    }
  }

  private string contentType;

  /// <summary>
  /// 圖片對應的MIME類型
  /// </summary>
  public string ContentType
  {
    get
    {
      return contentType;
    }

    set
    {
      contentType = value;
    }
  }
}

Html Demo

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Upload Images</title>
  <script src="swfupload/swfupload.js"></script>
  <script src="swfupload/handlers.js"></script>
  <script>
    //注:div的id名稱最好不要改,要改的話在handlers.js文件中也要進行修改,div的名稱已經在handlers.js文件中寫死
    var swfu;
    window.onload = function () {
      swfu = new SWFUpload({
        // 後台設置,設置處理上傳的頁面
        upload_url: "/Handlers/ImageUploadHandler.ashx",
        // 文件上傳大小限制設置
        file_size_limit: "3 MB",
        //文件類型設置,多種格式以英文中的分號分開
        file_types: "*.jpg;*.png",
        //文件描述,與彈出的選擇文件對話框相關
        file_types_description : "Images file",
        //設置上傳文件數量限制
        file_upload_limit: "1",

        //事件處理程序,最好不要改,事件處理程序已在handlers.js文件中定義
        // Event Handler Settings - these functions as defined in Handlers.js
        // The handlers are not part of SWFUpload but are part of my website and control how
        // my website reacts to the SWFUpload events.
        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler : fileDialogComplete,
        upload_progress_handler : uploadProgress,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : uploadComplete,

        // 上傳按鈕設置
        button_image_url : "/swfupload/images/XPButtonNoText_160x22.png",
        button_placeholder_id: "spanButtonPlaceholder",
        button_width: 160,
        button_height: 22,
        button_text : '請選擇圖片 (最大3M)',
        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,

        // swfupload.swf flash設置
        flash_url : "/swfupload/swfupload.swf",  
        //自定義的其他設置
        custom_settings : {
          upload_target: "divFileProgressContainer"
        },
        // 是否開啟調試模式,調試時可以設置為true,發布時設置為false
        debug: false
      });
    }
  </script>
</head>
<body>
  <form id="form1">
    <div id="content">
        <h2>Upload Images Demo</h2>
    
    <div id="swfu_container" style="margin: 0px 10px;">
      <div>
        <span id="spanButtonPlaceholder"></span>
      </div>
      <div id="divFileProgressContainer" style="height: 75px;"></div>
      <div id="thumbnails"></div>
    </div>
    </div>
  </form>
</body>
</html>

ImageUploadHandler

/// <summary>
  /// 圖片上傳處理
  /// </summary>
  public class ImageUploadHandler : IHttpHandler, IRequiresSessionState
  {
    /// <summary>
    /// 記錄日志 logger
    /// </summary>
    private static Common.LogHelper logger = new Common.LogHelper(typeof(ImageUploadHandler));
    public void ProcessRequest(HttpContext context)
    {
      context.Response.ContentType = "text/plain";
      System.Drawing.Image thumbnail_image = null;
      System.Drawing.Image original_image = null;
      System.Drawing.Bitmap final_image = null;
      System.Drawing.Graphics graphic = null;
      MemoryStream ms = null;
      try
      {
        //驗證用戶是否登錄,是否有權限上傳
        if (context.Session["User"]==null)
        {
          context.Response.Write("沒有上傳圖片的權限!");
          context.Response.End();
          return;
        }
        //獲取上傳文件
        HttpPostedFile image_upload = context.Request.Files["Filedata"];
        //獲取文件擴展名
        string fileExt = System.IO.Path.GetExtension(image_upload.FileName).ToLower();
        //驗證文件擴展名是否符合要求,是否是允許的圖片格式
        if (fileExt!=".jpg"&&fileExt!=".png")
        {
          return;
        }
        //當前時間字符串
        string timeString = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        //圖片保存虛擬路徑構建
        string path = "/Upload/"+timeString + fileExt;
        //保存到Session 變量中
        context.Session["imgPath"] = path;
        //獲取、構建要上傳文件的物理路徑
        string serverPath = context.Server.MapPath("~/"+path);
        //保存圖片到服務器
        image_upload.SaveAs(serverPath);
        //記錄日志
        logger.Debug("圖片上傳成功!");
        #region 生成縮略圖

        // 獲取上傳圖片的文件流
        original_image = System.Drawing.Image.FromStream(image_upload.InputStream);

        // 根據原圖計算縮略圖的寬度和高度,及縮放比例等~~
        int width = original_image.Width;
        int height = original_image.Height;
        int target_width = 100;
        int target_height = 100;
        int new_width, new_height;

        float target_ratio = (float)target_width / (float)target_height;
        float image_ratio = (float)width / (float)height;

        if (target_ratio > image_ratio)
        {
          new_height = target_height;
          new_width = (int)Math.Floor(image_ratio * (float)target_height);
        }
        else
        {
          new_height = (int)Math.Floor((float)target_width / image_ratio);
          new_width = target_width;
        }

        new_width = new_width > target_width ? target_width : new_width;
        new_height = new_height > target_height ? target_height : new_height;

        //創建縮略圖
        final_image = new System.Drawing.Bitmap(target_width, target_height);
        graphic = System.Drawing.Graphics.FromImage(final_image);
        graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, target_width, target_height));
        int paste_x = (target_width - new_width) / 2;
        int paste_y = (target_height - new_height) / 2;
        graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
                                                      //graphic.DrawImage(thumbnail_image, paste_x, paste_y, new_width, new_height);
        graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height);

        // Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo)
        ms = new MemoryStream();
        //將縮略圖保存到內存流中
        final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

        #endregion

        //建立 Thumbnail對象
        Thumbnail thumb = new Thumbnail(timeString, ms.GetBuffer());
        //保存縮略圖到Session 中,也可以保存成文件,保存為圖片
        context.Session["file_info"] = thumb;
        //操作成功,返回HTTP狀態碼設置為 200
        context.Response.StatusCode = 200;
        //輸出縮略圖的id,在生成縮略圖時要用到
        context.Response.Write(thumb.ID);
      }
      catch(Exception ex)
      {
        // 出現異常,返回 500,服務器內部錯誤
        context.Response.StatusCode = 500;
        //記錄錯誤日志
        logger.Error(ex);
      }
      finally
      {
        // 釋放資源
        if (final_image != null) final_image.Dispose();
        if (graphic != null) graphic.Dispose();
        if (original_image != null) original_image.Dispose();
        if (thumbnail_image != null) thumbnail_image.Dispose();
        if (ms != null) ms.Close();
        context.Response.End();
      }
    }

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

GetThumbHandler

/// <summary>
  /// 獲取縮略圖
  /// </summary>
  public class GetThumbHandler : IHttpHandler, IRequiresSessionState
  {
    public void ProcessRequest(HttpContext context)
    {
      context.Response.ContentType = "text/plain";
      //獲取縮略圖id
      string id = context.Request.QueryString["id"];
      //id為空則返回錯誤
      if (String.IsNullOrEmpty(id))
      {
        context.Response.StatusCode = 404;
        context.Response.Write("Not Found");
        context.Response.End();
        return;
      }
      //從Session中獲取縮略圖文件
      Thumbnail thumb= context.Session["file_info"] as Thumbnail;
      //判斷id是否一致
      if (thumb.ID == id)
      {
        //重新設置響應MIME 類型
        context.Response.ContentType = "image/png";
        //輸出二進制流信息
        context.Response.BinaryWrite(thumb.Data);
        //截止輸出
        context.Response.End();
        return;
      }

      //沒有找到相應圖片,返回404
      context.Response.StatusCode = 404;
      context.Response.Write("Not Found");
      context.Response.End();
    }

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

handlers.js 文件

function fileQueueError(file, errorCode, message) {
  try {
    var imageName = "error.gif";
    var errorName = "";
    if (errorCode == SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
      errorName = "上傳文件過多!";
    }

    if (errorName != "") {
      alert(errorName);
      return;
    }

    switch (errorCode) {
    case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
      imageName = "zerobyte.gif";
      break;
    case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
      imageName = "toobig.gif";
      break;
    case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
    case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
    default:
      alert(message);
      break;
    }
    //添加圖片,注意路徑
    addImage("/swfupload/images/" + imageName);

  } catch (ex) {
    this.debug(ex);
  }

}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
  try {
    if (numFilesQueued > 0) {
      this.startUpload();
    }
  } catch (ex) {
    this.debug(ex);
  }
}

function uploadProgress(file, bytesLoaded) {

  try {
    var percent = Math.ceil((bytesLoaded / file.size) * 100);

    var progress = new FileProgress(file, this.customSettings.upload_target);
    progress.setProgress(percent);
    if (percent === 100) {
      progress.setStatus("正在創建縮略圖...");
      progress.toggleCancel(false, this);
    } else {
      progress.setStatus("正在上傳...");
      progress.toggleCancel(true, this);
    }
  } catch (ex) {
    this.debug(ex);
  }
}

function uploadSuccess(file, serverData) {
  try {
    //添加縮略圖~~~
    //修改這裡來設置生成縮略圖的頁面
    addImage("/Handlers/GetThumbHandler.ashx?id=" + serverData);
    var progress = new FileProgress(file, this.customSettings.upload_target);
    progress.setStatus("縮略圖創建成功!");
    progress.toggleCancel(false);
  } catch (ex) {
    this.debug(ex);
  }
}

function uploadComplete(file) {
  try {
    /* I want the next upload to continue automatically so I'll call startUpload here */
    if (this.getStats().files_queued > 0) {
      this.startUpload();
    } else {
      var progress = new FileProgress(file, this.customSettings.upload_target);
      progress.setComplete();
      progress.setStatus("圖片上傳成功");
      progress.toggleCancel(false);
    }
  } catch (ex) {
    this.debug(ex);
  }
}

function uploadError(file, errorCode, message) {
  var imageName = "error.gif";
  var progress;
  try {
    switch (errorCode) {
    case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
      try {
        progress = new FileProgress(file, this.customSettings.upload_target);
        progress.setCancelled();
        progress.setStatus("上傳操作被取消");
        progress.toggleCancel(false);
      }
      catch (ex1) {
        this.debug(ex1);
      }
      break;
    case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
      try {
        progress = new FileProgress(file, this.customSettings.upload_target);
        progress.setCancelled();
        progress.setStatus("上傳停止!");
        progress.toggleCancel(true);
      }
      catch (ex2) {
        this.debug(ex2);
      }
    case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
      imageName = "uploadlimit.gif";
      break;
    default:
      alert(message);
      break;
    }

    addImage("/swfupload/images/" + imageName);

  } catch (ex3) {
    this.debug(ex3);
  }

}

function addImage(src) {
  var newImg = document.createElement("img");
  newImg.style.margin = "5px";
  document.getElementById("thumbnails").appendChild(newImg);
  if (newImg.filters) {
    try {
      newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
    } catch (e) {
      // If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
      newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
    }
  } else {
    newImg.style.opacity = 0;
  }

  newImg.onload = function () {
    fadeIn(newImg, 0);
  };
  newImg.src = src;
}

function fadeIn(element, opacity) {
  var reduceOpacityBy = 5;
  var rate = 30;  // 15 fps


  if (opacity < 100) {
    opacity += reduceOpacityBy;
    if (opacity > 100) {
      opacity = 100;
    }

    if (element.filters) {
      try {
        element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
      } catch (e) {
        // If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
        element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
      }
    } else {
      element.style.opacity = opacity / 100;
    }
  }

  if (opacity < 100) {
    setTimeout(function () {
      fadeIn(element, opacity);
    }, rate);
  }
}

/* ******************************************
 *  FileProgress Object
 *  Control object for displaying file info
 * ****************************************** */

function FileProgress(file, targetID) {
  this.fileProgressID = "divFileProgress";

  this.fileProgressWrapper = document.getElementById(this.fileProgressID);
  if (!this.fileProgressWrapper) {
    this.fileProgressWrapper = document.createElement("div");
    this.fileProgressWrapper.className = "progressWrapper";
    this.fileProgressWrapper.id = this.fileProgressID;

    this.fileProgressElement = document.createElement("div");
    this.fileProgressElement.className = "progressContainer";

    var progressCancel = document.createElement("a");
    progressCancel.className = "progressCancel";
    progressCancel.href = "#";
    progressCancel.style.visibility = "hidden";
    progressCancel.appendChild(document.createTextNode(" "));

    var progressText = document.createElement("div");
    progressText.className = "progressName";
    progressText.appendChild(document.createTextNode(file.name));

    var progressBar = document.createElement("div");
    progressBar.className = "progressBarInProgress";

    var progressStatus = document.createElement("div");
    progressStatus.className = "progressBarStatus";
    progressStatus.innerHTML = " ";

    this.fileProgressElement.appendChild(progressCancel);
    this.fileProgressElement.appendChild(progressText);
    this.fileProgressElement.appendChild(progressStatus);
    this.fileProgressElement.appendChild(progressBar);

    this.fileProgressWrapper.appendChild(this.fileProgressElement);

    document.getElementById(targetID).appendChild(this.fileProgressWrapper);
    fadeIn(this.fileProgressWrapper, 0);

  } else {
    this.fileProgressElement = this.fileProgressWrapper.firstChild;
    this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name;
  }

  this.height = this.fileProgressWrapper.offsetHeight;

}
FileProgress.prototype.setProgress = function (percentage) {
  this.fileProgressElement.className = "progressContainer green";
  this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
  this.fileProgressElement.childNodes[3].style.width = percentage + "%";
};
FileProgress.prototype.setComplete = function () {
  this.fileProgressElement.className = "progressContainer blue";
  this.fileProgressElement.childNodes[3].className = "progressBarComplete";
  this.fileProgressElement.childNodes[3].style.width = "";

};
FileProgress.prototype.setError = function () {
  this.fileProgressElement.className = "progressContainer red";
  this.fileProgressElement.childNodes[3].className = "progressBarError";
  this.fileProgressElement.childNodes[3].style.width = "";

};
FileProgress.prototype.setCancelled = function () {
  this.fileProgressElement.className = "progressContainer";
  this.fileProgressElement.childNodes[3].className = "progressBarError";
  this.fileProgressElement.childNodes[3].style.width = "";

};
FileProgress.prototype.setStatus = function (status) {
  this.fileProgressElement.childNodes[2].innerHTML = status;
};
FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) {
  this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
  if (swfuploadInstance) {
    var fileID = this.fileProgressID;
    this.fileProgressElement.childNodes[0].onclick = function () {
      swfuploadInstance.cancelUpload(fileID);
      return false;
    };
  }
};

以上所述就是本文的全部內容了,希望對大家學習asp.net能夠有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved