使用SWFUpload组件无刷新上传图片

在做项目时,需要用到一个图片的无刷新上传,之前听说过SWFUpload,于是想要通过SWFUpload来进行图片的无刷新上传,由于我的项目属于是ASP.NET项目,所以本文着重讲解ASP.NET 的使用,个人感觉示例基本给的很清晰,参考文档进行开发,并非难事

0.     首先下载swfUpload 包,在下载的包中有samples文件夹,samples下有demos文件夹,打开demos文件夹可看到如下图所示结构

我们待会会用到的包括,swfupload目录下的文件,css不建议使用以避免与自己写的CSS相冲突使得页面布局完全乱掉,如果要添加样式最好自己写

打开 applicationdemo.net目录会看到这样的结构

打开index.html可以看到这样的页面

点击NET2.0下的Application Demo C#项

  1. 添加资源引用

将要引用的资源包含到项目中(包括swfupload文件夹下的文件与,demo下的资源文件,handlers.js是在demo中js目录下的js文件)

  1. 首先熟悉demo,将demo中的页面包含到项目中

    在Defaut.aspx页面中使用swfUpload组件进行图片的无刷新上传直接运行,看效果,大概了解基本过程

  2. 修改handlers.js文件

    我的项目文件结构大概是这样的

    我的处理文件上传的页面是ImageUploadHandler.ashx,获取缩略图的页面是GetThumbHandler.ashx,Thumbnail.cs是demo中App_Code文件夹中的文件,个人觉得像这种只处理逻辑功能而不展现页面的最好都用一般处理程序来实现。由于哪个文件处理上传哪个文件生成缩略图已经在handlers.js文件中写死了,所以必须要修改handlers.js文件以能够使页面正常运行

  3. 最终修改版汇总

     /// <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;
    }
    }
    }

    Thumbnail

    <!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>

    Html Demo

         /// <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 = ;
    int target_height = ;
    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(, , target_width, target_height));
    int paste_x = (target_width - new_width) / ;
    int paste_y = (target_height - new_height) / ;
    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 = ;
    //输出缩略图的id,在生成缩略图时要用到
    context.Response.Write(thumb.ID);
    }
    catch(Exception ex)
    {
    // 出现异常,返回 500,服务器内部错误
    context.Response.StatusCode = ;
    //记录错误日志
    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;
    }
    }
    }

    ImageUploadHandler

         /// <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 = ;
    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 = ;
    context.Response.Write("Not Found");
    context.Response.End();
    } public bool IsReusable
    {
    get
    {
    return false;
    }
    }
    }

    GetThumbHandler

     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;
    };
    }
    };

    handlers.js 文件

使用SWFUpload无刷新上传图片的更多相关文章

  1. nodejs利用ajax实现网页无刷新上传图片

    nodejs利用ajax实现网页无刷新上传图片 标签(空格分隔): nodejs 通常情况下上传图片是要通过提交form表单来实现的,但是这又不可避免的产生了网页转. 利用ajax技术和FormDat ...

  2. php无刷新上传图片和文件

    核心思想:通过Html的iframe标签属性操作顶级窗口,再用php动态无刷新上传图片文件. 示例如下: demo |------uploads #存放上传的文件 |------index.php | ...

  3. Thinkphp框架 -- ajax无刷新上传图片

    用Thinkphp框架做无刷新上传图片 视图层 View <!doctype html> <html lang="en"> <head> < ...

  4. ajaxFileUpload.js 无刷新上传图片,支持多个参数同时上传,支持 ie6-ie10

    /* 131108-xxj-ajaxFileUpload.js 无刷新上传图片 jquery 插件,支持 ie6-ie10 依赖:jquery-1.6.1.min.js 主方法:ajaxFileUpl ...

  5. TP3.2:实现Ajax无刷新上传图片

    1.基于TP3.2+ajaxfileupload进行无刷新上传图片,本次只上传一张,多张以后搞出来再发 2.效果:   3.html代码: <html> <head> < ...

  6. 无刷新上传图片,ajax 和 iframe

    iframe 上传 upload.html 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 ...

  7. ajax无刷新上传图片

    页面: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> & ...

  8. SWFUpload无刷新文件批量上传

    一.首先将SWFUpload所有文件加入项目中,如图

  9. js无刷新上传图片,服务端有生成缩略图,剪切图片,iphone图片旋转判断功能

    html: <form action="<{:AppLink('circle/uploadimg')}>" id="imageform" me ...

随机推荐

  1. 250W电源带i7+GTX1080?

    电源的科学: Q1:电源的额定功率是什么?峰值功率又是什么?A1:电源的额定功率就是电源正常工作时的功率,它的值为用电器的额定电压乘以额定电流.而峰值功率指的是电源短时间内能达到的最大功率, 一般情况 ...

  2. Changing Project Binding to Surround SCM Integration Provider with Visual Studio 2010

    Changing Project Binding to Surround SCM Integration Provider with Visual Studio 2010 Sarah Wigser t ...

  3. Tomcat Manager 用户名和密码配置

    在Tomcat中,应用程序的部署很简单,只需将你的WAR放到Tomcat的webapp目录下,Tomcat会自动检测到这个文件,并将其解压.在浏览器中访问这个应用的Jsp时,通常第一次会很慢,因为To ...

  4. ubuntu 添加管理员账户

    sudo adduser cat 输入密码即可 sudo adduser cat sudo 为cat 添加sudo 权限

  5. CG

    //设置线的宽度 CGContextSetLineWidth(ctx, 12); //设置线的连接处 (拐点) CGContextSetLineJoin(ctx, kCGLineJoinRound ) ...

  6. 界面排版-TableLayout的stretchColumns方法

    1.先把XML內的預設RelativeLayout排版方式清空,在去Layout區拉一個TableLayout的到表單上,XML下會出現下面程式碼       <TableLayout xmln ...

  7. 实战android菜单项之XML加载菜单与动态菜单项[转]

    原文地址:http://blog.csdn.net/kaiwii/article/details/7767225 自定义android应用程序的菜单项首先要知道切入点.经过学习,知道主要是两个Acti ...

  8. java攻城狮之路(Android篇)--与服务器交互

    一.图片查看器和网页源码查看器 在输入地址的是不能输入127.0.0.1 或者是 localhost.ScrollView :可以看成一个滚轴 可以去包裹很多的控件在里面 练习1(图片查看器): pa ...

  9. Django Push HTTP Response to users

    Django Push HTTP Response to users I currently have a very simple web application written in Django, ...

  10. vmware虚拟机工具vmware tools介绍及安装排错

    VMware Tools是VMware虚拟机中自带的一种增强工具,相当于VirtualBox中的增强功能(Sun VirtualBox Guest Additions),是VMware提供的增强虚拟显 ...