加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

使用SWFUpload无刷新上传图片

发布时间:2020-12-16 09:00:06 所属栏目:asp.Net 来源:网络整理
导读:使用SWFUpload组件无刷新上传图片 在做项目时,需要用到一个图片的无刷新上传,之前听说过SWFUpload,于是想要通过SWFUpload来进行图片的无刷新上传,由于我的项目属于是ASP.NET项目,所以本文着重讲解ASP.NET 的使用,个人感觉示例基本给的很清晰,参考文档

使用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. 最终修改版汇总

    ?

     1 /// <summary>
     2 /// 缩略图
     3 </summary>
     4 public class Thumbnail
     5 {
     6     public Thumbnail(string id,byte[] data)
     7     {
     8         this.ID = id;
     9         this.Data = data;
    10     }
    11 
    12     private string13 
    14     15      图片id
    16     17      ID
    18 19         get
    20         {
    21             return this.id;
    22         }
    23         set
    24 25             this.id = value;
    26 27 28 
    29     [] thumbnail_data;
    30 
    31     32      图片的二进制数据
    33     34     [] Data
    35 36         37 38             .thumbnail_data;
    39 40         41 42             this.thumbnail_data =43 44 45 
    46      contentType;
    47 
    48     49      图片对应的MIME类型
    50     51      ContentType
    52 53         54 55             return56 57 
    58         59 60             contentType =61 62 63 }
    Thumbnail

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    head>
        title>Upload Images</script src="swfupload/swfupload.js"></script="swfupload/handlers.js">
            //注: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,1)"> 上传按钮设置
                    button_image_url : /swfupload/images/XPButtonNoText_160x22.pngspanButtonPlaceholder16022'请选择图片 (最大3M).button { font-family: Helvetica,Arial,sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }5 swfupload.swf flash设置
                    flash_url : /swfupload/swfupload.swf自定义的其他设置
                    custom_settings : {
                        upload_target: divFileProgressContainer
                    },1)"> 是否开启调试模式,调试时可以设置为true,发布时设置为false
                    debug: false
                });
            }
        bodyform id="form1">
            div ="content">
                    h2>Upload Images Demo>
            
            ="swfu_container" style="margin: 0px 10px;">
                divspan ="spanButtonPlaceholder"span="divFileProgressContainer"="height: 75px;"="thumbnails"formhtml>
    Html Demo

      1       2      图片上传处理
      3       4      ImageUploadHandler : IHttpHandler,IRequiresSessionState
      5   6           7          记录日志 logger
      8           9         static Common.LogHelper logger = new Common.LogHelper(typeof(ImageUploadHandler));
     10         void ProcessRequest(HttpContext context)
     11  12             context.Response.ContentType = "text/plain";
     13             System.Drawing.Image thumbnail_image = null 14             System.Drawing.Image original_image =  15             System.Drawing.Bitmap final_image =  16             System.Drawing.Graphics graphic =  17             MemoryStream ms =  18             try
     19             {
     20                 //验证用户是否登录,是否有权限上传
     21                 if (context.Session[User"]==)
     22                 {
     23                     context.Response.Write(没有上传图片的权限!);
     24                     context.Response.End();
     25                      26                 }
     27                 获取上传文件
     28                 HttpPostedFile image_upload = context.Request.Files[Filedata];
     29                 获取文件扩展名
     30                 string fileExt = System.IO.Path.GetExtension(image_upload.FileName).ToLower();
     31                 验证文件扩展名是否符合要求,是否是允许的图片格式
     32                 if (fileExt!=.jpg"&&fileExt!=.png 33  34                      35  36                 当前时间字符串
     37                 string timeString = DateTime.Now.ToString(yyyyMMddHHmmssfff 38                 图片保存虚拟路径构建
     39                 string path = /Upload/"+timeString + fileExt;
     40                 保存到Session 变量中
     41                 context.Session[imgPath"] = path;
     42                 获取、构建要上传文件的物理路径
     43                 string serverPath = context.Server.MapPath(~/"+path);
     44                 保存图片到服务器
     45                 image_upload.SaveAs(serverPath);
     46                 记录日志
     47                 logger.Debug(图片上传成功! 48                 #region 生成缩略图
     49 
     50                  获取上传图片的文件流
     51                 original_image = System.Drawing.Image.FromStream(image_upload.InputStream);
     52 
     53                  根据原图计算缩略图的宽度和高度,及缩放比例等~~
     54                 int width = original_image.Width;
     55                 int height = original_image.Height;
     56                 int target_width = 100 57                 int target_height =  58                 int new_width,new_height;
     59 
     60                 float target_ratio = (float)target_width / (float)target_height;
     61                 float image_ratio = (float)width / ()height;
     62 
     63                 if (target_ratio > image_ratio)
     64  65                     new_height = target_height;
     66                     new_width = (int)Math.Floor(image_ratio * ()target_height);
     67  68                 else
     69  70                     new_height = (int)Math.Floor((float)target_width / image_ratio);
     71                     new_width = target_width;
     72  73 
     74                 new_width = new_width > target_width ? target_width : new_width;
     75                 new_height = new_height > target_height ? target_height : new_height;
     76 
     77                 创建缩略图
     78                 final_image = new System.Drawing.Bitmap(target_width,target_height);
     79                 graphic = System.Drawing.Graphics.FromImage(final_image);
     80                 graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black),1)">new System.Drawing.Rectangle(0,0 81                 int paste_x = (target_width - new_width) / 2 82                 int paste_y = (target_height - new_height) /  83                 graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
     84                                                                                                            graphic.DrawImage(thumbnail_image,paste_x,paste_y,new_width,new_height);
     85                 graphic.DrawImage(original_image,new_height);
     86 
     87                  Store the thumbnail in the session (Note: this is bad,it will take a lot of memory,but this is just a demo)
     88                 ms =  MemoryStream();
     89                 将缩略图保存到内存流中
     90                 final_image.Save(ms,System.Drawing.Imaging.ImageFormat.Png);
     91 
     92                 #endregion
     93 
     94                 建立 Thumbnail对象
     95                 Thumbnail thumb =  Thumbnail(timeString,ms.GetBuffer());
     96                 保存缩略图到Session 中,也可以保存成文件,保存为图片
     97                 context.Session[file_info thumb;
     98                 操作成功,返回HTTP状态码设置为 200
     99                 context.Response.StatusCode = 200100                 输出缩略图的id,在生成缩略图时要用到
    101                 context.Response.Write(thumb.ID);
    102             }
    103             catch(Exception ex)
    104 105                  出现异常,返回 500,服务器内部错误
    106                 context.Response.StatusCode = 500107                 记录错误日志
    108                 logger.Error(ex);
    109 110             finally
    111 112                  释放资源
    113                 if (final_image != ) final_image.Dispose();
    114                 if (graphic != ) graphic.Dispose();
    115                 if (original_image != ) original_image.Dispose();
    116                 if (thumbnail_image != ) thumbnail_image.Dispose();
    117                 if (ms != ) ms.Close();
    118                 context.Response.End();
    119 120 121 
    122         bool IsReusable
    123 124             125 126                 false127 128 129     }
    ImageUploadHandler

     1      2      获取缩略图
     3      4      GetThumbHandler : IHttpHandler,1)"> 6          8             context.Response.ContentType =  9             获取缩略图id
    10             string id = context.Request.QueryString[id11             id为空则返回错误
    12             if (String.IsNullOrEmpty(id))
    13 14                 context.Response.StatusCode = 40415                 context.Response.Write(Not Found16 17                 19             从Session中获取缩略图文件
    20             Thumbnail thumb= context.Session["] as Thumbnail;
    判断id是否一致
    22             if (thumb.ID == id)
    23 24                 重新设置响应MIME 类型
    25                 context.Response.ContentType = image/png26                 输出二进制流信息
                    context.Response.BinaryWrite(thumb.Data);
    28                 截止输出
    29 30                 31 32 
    33             没有找到相应图片,返回404
    34             context.Response.StatusCode = 35             context.Response.Write(36             context.Response.End();
    38 
    39         40 41             42 43                 45 46     }
    GetThumbHandler

      1 function fileQueueError(file,errorCode,message) {
      2     try {
      3         var imageName = "error.gif"  4         var errorName = ""  5         if (errorCode == SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
      6             errorName = "上传文件过多!"  7   8 
    if (errorName != "") {
     10             alert(errorName);
     11              12  13 
     14         switch (errorCode) {
     15         case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
     16             imageName = "zerobyte.gif" 17             break 18          SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
     19             imageName = "toobig.gif" 20              21          22          SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
     23         default:
                alert(message);
     25              27         添加图片,注意路径
     28         addImage("/swfupload/images/" + imageName);
     29 
     30     }  (ex) {
     31         .debug(ex);
     32  33 
     34 }
     35 
     36  fileDialogComplete(numFilesSelected,numFilesQueued) {
     37      38         if (numFilesQueued > 0 39             .startUpload();
     40  41     }  42          43  44  45 
     46  uploadProgress(file,bytesLoaded) {
     47 
     48      49         var percent = Math.ceil((bytesLoaded / file.size) * 100 50 
     51         var progress = new FileProgress(file,1)">.customSettings.upload_target);
     52         progress.setProgress(percent);
     53         if (percent === 100 54             progress.setStatus("正在创建缩略图..." 55             progress.toggleCancel(false,1)"> 56         } else 57             progress.setStatus("正在上传..." 58             progress.toggleCancel(true,1)"> 59  60     }  61          62  63  64 
     65  uploadSuccess(file,serverData) {
     66      67         添加缩略图~~~
     68         修改这里来设置生成缩略图的页面
     69         addImage("/Handlers/GetThumbHandler.ashx?id=" + serverData);
     70          71         progress.setStatus("缩略图创建成功!" 72         progress.toggleCancel( 73     }  74          75  76  77 
     78  uploadComplete(file) {
     79      80           I want the next upload to continue automatically so I'll call startUpload here  81         if (this.getStats().files_queued > 0 82              83         }  84                         progress.setComplete();
     86             progress.setStatus("图片上传成功" 87             progress.toggleCancel( 88  89     }  90          91  92  94  uploadError(file,1)"> 95     var imageName =  "error.gif" 96     var progress;
     97      98          99          SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
    100             101                 progress =                 progress.setCancelled();
    103                 progress.setStatus("上传操作被取消"104                 progress.toggleCancel(105 106              (ex1) {
    .debug(ex1);
    109             110          SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
    111             112                 progress = 113 114                 progress.setStatus("上传停止!"115                 progress.toggleCancel(true116 117              (ex2) {
    118                 .debug(ex2);
    120          SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
    121             imageName = "uploadlimit.gif"122             123         124 125             126 127 
    128         addImage("/swfupload/images/" +129 
    130     }  (ex3) {
    131         .debug(ex3);
    132 133 
    134 135 
    136  addImage(src) {
    137     var newImg = document.createElement("img"138     newImg.style.margin = "5px"139     document.getElementById("thumbnails").appendChild(newImg);
    140      (newImg.filters) {
    141         142             newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0143         }  (e) {
    144              If it is not set initially,the browser will throw an error.  This will set it if it is not set yet.
    145             newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')'146 147     } 148         newImg.style.opacity = 0149 150 
    151     newImg.onload =  () {
    152         fadeIn(newImg,0153     };
    154     newImg.src = src;
    155 156 
    157  fadeIn(element,opacity) {
    158     var reduceOpacityBy = 5159     var rate = 30;     15 fps
    160 
    161 
    162     if (opacity < 100163         opacity += reduceOpacityBy;
    164         if (opacity > 100165             opacity = 100166 167 
    168          (element.filters) {
    169             170                 element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
    171             } 172                 173                 element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')'174 175         } 176             element.style.opacity = opacity / 100177 178 179 
    180     181         setTimeout(182             fadeIn(element,opacity);
    183         },rate);
    184 185 186 
    187  ******************************************
    188  *    FileProgress Object
    189  *    Control object for displaying file info
    190  * ****************************************** 191 
    192  FileProgress(file,targetID) {
    193     this.fileProgressID = "divFileProgress"194 
    195     this.fileProgressWrapper = document.getElementById(.fileProgressID);
    196     if (!.fileProgressWrapper) {
    197         this.fileProgressWrapper = document.createElement("div"198         this.fileProgressWrapper.className = "progressWrapper"199         this.fileProgressWrapper.id = .fileProgressID;
    200 
    201         this.fileProgressElement = document.createElement("div"202         this.fileProgressElement.className = "progressContainer"203 
    204         var progressCancel = document.createElement("a"205         progressCancel.className = "progressCancel"206         progressCancel.href = "#"207         progressCancel.style.visibility = "hidden"208         progressCancel.appendChild(document.createTextNode(" "));
    209 
    210         var progressText = document.createElement("div"211         progressText.className = "progressName"212         progressText.appendChild(document.createTextNode(file.name));
    213 
    214         var progressBar = document.createElement("div"215         progressBar.className = "progressBarInProgress"216 
    217         var progressStatus = document.createElement("div"218         progressStatus.className = "progressBarStatus"219         progressStatus.innerHTML = "&nbsp;"220 
    221         .fileProgressElement.appendChild(progressCancel);
    222         .fileProgressElement.appendChild(progressText);
    223         .fileProgressElement.appendChild(progressStatus);
    224         .fileProgressElement.appendChild(progressBar);
    225 
    226         this.fileProgressWrapper.appendChild(.fileProgressElement);
    227 
    228         document.getElementById(targetID).appendChild(.fileProgressWrapper);
    229         fadeIn(this.fileProgressWrapper,1)">230 
    231     } 232         this.fileProgressElement = .fileProgressWrapper.firstChild;
    233         this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name;
    234 235 
    236     this.height = .fileProgressWrapper.offsetHeight;
    237 
    238 239 FileProgress.prototype.setProgress =  (percentage) {
    240     this.fileProgressElement.className = "progressContainer green"241     this.fileProgressElement.childNodes[3].className = "progressBarInProgress"242     this.fileProgressElement.childNodes[3].style.width = percentage + "%"243 };
    244 FileProgress.prototype.setComplete = 245     this.fileProgressElement.className = "progressContainer blue"246     this.fileProgressElement.childNodes[3].className = "progressBarComplete"247     this.fileProgressElement.childNodes[3].style.width = ""248 
    249 250 FileProgress.prototype.setError = 251     this.fileProgressElement.className = "progressContainer red"252     this.fileProgressElement.childNodes[3].className = "progressBarError"253     254 
    255 256 FileProgress.prototype.setCancelled = 257     258     259     260 
    261 262 FileProgress.prototype.setStatus =  (status) {
    263     this.fileProgressElement.childNodes[2].innerHTML = status;
    264 265 FileProgress.prototype.toggleCancel =  (show,swfuploadInstance) {
    266     this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden"267      (swfuploadInstance) {
    268         var fileID = 269         this.fileProgressElement.childNodes[0].onclick = 270             swfuploadInstance.cancelUpload(fileID);
    271             272         };
    273 274 };
    handlers.js 文件

    ?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读