SWF Upload 를 사용 하여 새로 고침 없 이 사진 을 업로드 합 니 다.

프로젝트 를 할 때 한 이미지 의 리 셋 없 는 업로드 가 필요 합 니 다.전에 SWF Upload 라 는 말 을 들 었 기 때문에 SWF Upload 를 통 해 이미지 의 리 셋 없 는 업 로드 를 하려 고 합 니 다.제 프로젝트 는 ASP.NET 프로젝트 에 속 하기 때문에 본 고 는 ASP.NET 의 사용 에 중심 을 두 고 설명 하고 자 합 니 다.개인 적 인 느낌 사례 는 대체적으로 뚜렷 하고 문 서 를 참고 하여 개발 하 는 것 이 어렵 지 않 습 니 다.
0.우선다운로드 하 다.swfUpload 패키지,다운로드 한 패키지 에 samples 폴 더,samples 에 demos 폴 더 가 있 습 니 다.demos 폴 더 를 열 면 다음 그림 과 같은 구 조 를 볼 수 있 습 니 다.
이 따 swfupload 디 렉 터 리 에 있 는 파일 을 포함 하여 css 는 자신 이 쓴 CSS 와 충돌 하지 않도록 사용 하 는 것 을 권장 하지 않 습 니 다.스타일 을 추가 하려 면 직접 쓰 는 것 이 좋 습 니 다.

applicationdemo.net 디 렉 터 리 를 열 면 이런 구 조 를 볼 수 있 습 니 다.

index.html 를 열 면 이런 페이지 를 볼 수 있 습 니 다.

NET 2.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 = "&nbsp;";

    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 을 배 우 는 데 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기