使用SWFUpload实现无刷新上传图片

434 查看

在做项目时,需要用到一个图片的无刷新上传,之前听说过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能够有所帮助。