您现在的位置是:网站首页> 编程资料编程资料
使用SWFUpload实现无刷新上传图片_实用技巧_
2023-05-24
235人已围观
简介 使用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#项

添加资源引用
将要引用的资源包含到项目中(包括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
////// 缩略图 /// public class Thumbnail { public Thumbnail(string id, byte[] data) { this.ID = id; this.Data = data; } private string id; ////// 图片id /// public string ID { get { return this.id; } set { this.id = value; } } private byte[] thumbnail_data; ////// 图片的二进制数据 /// public byte[] Data { get { return this.thumbnail_data; } set { this.thumbnail_data = value; } } private string contentType; ////// 图片对应的MIME类型 /// public string ContentType { get { return contentType; } set { contentType = value; } } }
Html Demo
Upload Images
ImageUploadHandler
////// 图片上传处理 /// public class ImageUploadHandler : IHttpHandler, IRequiresSessionState { ////// 记录日志 logger /// 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
////// 获取缩略图 /// 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; } //添加图片,注意路径 addI
点击排行
本栏推荐
