jQuery + ashx 实现图片按比例预览、异步上传及显示
关键点:
- jquery.ajax 方法 和 HTML5 中的 FileReader对象
- ashx 处理程序
- asp.net 的 ScriptManager.RegisterStartupScript 调用客户端js脚本
一、ASP.NET 前台源码:
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="load_pic.aspx.cs" Inherits="Default2" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
- <script type="text/javascript" src="Scripts/jquery-extend.js"></script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <!-- 把浏览图片解析为 base64 字符串 ,通过 jQuery.ajax + ashx 异步保存到数据库中 -->
- <input type='file' onchange="readURL(this);" />
- <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="C#后台读取显示" />
- <!-- 存储 base64 字符串 ,方便在后台处理 -->
- <asp:HiddenField ID="hf_base64" runat="server" />
- </div>
- <div>
- <img id="img_prev" src="#" alt="your image" /></div>
- </form>
- </body>
- </html>
二、jquery-extent.js 代码
- /* 客户端按比例预览、上传图片 要求:jquery-1.4.1.min.js */
- //================================================================================================
- function readURL(input) {
- if (input.files && input.files[0]) {
- var reader = new FileReader();
- var maxWidth = 200, maxHeight = 200;
- reader.onload = function (e) {
- var base64 = e.target.result;
- loadbase64(base64, maxWidth, maxHeight);
- $("#hf_base64").val(base64);
- };
- reader.readAsDataURL(input.files[0]);
- }
- }
- // imgobj : img 标签对象,根据容器自动调整宽、高
- function load_obj_base64(imgobj, base64) {
- maxWidth = $(imgobj).width();
- maxHeight = $(imgobj).height();
- $("<img/>") // 在内存中创建一个img标记
- .attr("src", base64)
- .load(function () {
- var w, h;
- w = this.width;
- h = this.height;
- if (w < maxWidth && h < maxHeight) { }
- else
- { w / h > maxWidth / maxHeight ? this.width = maxWidth : this.height = maxHeight; }
- $(imgobj).replaceWith(this);
- });
- }
- function loadbase64(base64, maxWidth, maxHeight) {
- $("<img/>") // 在内存中创建一个img标记
- .attr("src", base64).attr("id", "img_prev")
- .load(function () {
- var w, h;
- w = this.width;
- h = this.height;
- // 当图片比预览区域小时不做任何改变
- if (w < maxWidth && h < maxHeight) { }
- else
- // 当实际图片比例大于预览区域宽高比例时
- // 缩放图片宽度,反之缩放图片宽度
- { w / h > maxWidth / maxHeight ? this.width = maxWidth : this.height = maxHeight; }
- $('#img_prev').replaceWith(this);
- $.ajax({
- async: false,
- type: 'POST',
- url: "uploadhandler.ashx",
- data: {
- file: base64
- },
- success: function (data) {
- //$j('#img_wait').css('display', 'none');
- },
- beforeSend: function (xhr) {
- //$j('#img_wait').css('display', 'inline');
- }
- });
- });
- }
三、uploadhandler.ashx
- <%@ WebHandler Language="C#" Class="uploadhandler" %>
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.IO;
- using System.Net;
- using System.Web;
- using System.Web.Services;
- [WebService(Namespace = "http://tempuri.org/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- public class uploadhandler : IHttpHandler
- {
- public void ProcessRequest(HttpContext context)
- {
- context.Response.ContentType = "text/plain";
- context.Response.Charset = "utf-8";
- try
- {
- HttpPostedFile file = context.Request.Files["Filedata"];
- DBUtility.IDBHelper dbhelper = new DBUtility.SqlHelper();
- string strSql = "UPDATE [LDZ] set Photo = @imagedata WHERE [ID] = 13;";
- byte[] buffer = null;
- if (file != null)
- {
- buffer = getByte(file);
- }
- else
- {
- string img = context.Request.Params["file"];
- img = img.Substring(img.IndexOf("base64,") + 7);
- buffer = Convert.FromBase64String(img);
- }
- int r = dbhelper.ExecuteNonQuery(WebConfig.DB_CONN, System.Data.CommandType.Text,
- strSql,new System.Data.SqlClient.SqlParameter("@imagedata", buffer));
- context.Response.Write("1");
- }
- catch (Exception ex)
- {
- context.Response.Write("0");
- }
- }
- private byte[] getByte(HttpPostedFile file)
- {
- byte[] buffer = new byte[file.ContentLength];
- file.InputStream.Read(buffer, 0, buffer.Length);
- return buffer;
- }
- public bool IsReusable
- {
- get
- {
- return false;
- }
- }
- //图片转为base64编码的字符串
- protected string ImgToBase64String(string Imagefilename)
- {
- try
- {
- System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Imagefilename);
- MemoryStream ms = new MemoryStream();
- bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
- byte[] arr = new byte[ms.Length];
- ms.Position = 0;
- ms.Read(arr, 0, (int)ms.Length);
- ms.Close();
- return Convert.ToBase64String(arr);
- }
- catch (Exception ex)
- {
- return null;
- }
- }
- //base64编码的字符串转为图片
- protected System.Drawing.Bitmap Base64StringToImage(string strbase64)
- {
- try
- {
- byte[] arr = Convert.FromBase64String(strbase64);
- MemoryStream ms = new MemoryStream(arr);
- System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);
- //bmp.Save("test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
- ms.Close();
- return bmp;
- }
- catch (Exception ex)
- {
- return null;
- }
- }
- }
四、ASP.NET 后台代码
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- public partial class Default2 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- DBUtility.IDBHelper dbhelper = new DBUtility.SqlHelper();
- string strSql = "select Photo from [LDZ] WHERE [ID] = 13;";
- DataSet r = dbhelper.ExecuteQuery(WebConfig.DB_CONN, System.Data.CommandType.Text, strSql);
- object imgObj = r.Tables[0].Rows[0]["Photo"];
- string base64 = "data:image/jpeg;base64,";
- if (imgObj != System.DBNull.Value)
- {
- byte[] buffer = (byte[])imgObj;
- base64 += Convert.ToBase64String(buffer);
- }
- string hf_base64 = this.hf_base64.Value;
- ScriptManager.RegisterStartupScript(this, this.GetType(), "",
- "loadbase64('" + base64 + "', 500, 500)", true);
- }
- }
注:ajax 方式异步读取数据库显示图片的方法同上传一致,使用 ashx 返回base64字符串在客户端处理即可。
记录一个让我纠结良久的问题:
在Page_Load 函数中,只有第一个用 ScriptManager.RegisterStartupScript 注册的脚本才有效
- /// <summary>
- /// 此函数范围内只有第一个用 ScriptManager.RegisterStartupScript 注册的脚本才有效
- /// </summary>
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- // 首次加载的处理方法
- if (this.Request.Params["lid"] != null)
- {
- // 照片处理,从数据获取过程省略......
- object imgObj = row["Photo"];
- string base64 = "data:image/jpeg;base64,";
- if (imgObj != System.DBNull.Value)
- {
- byte[] buffer = (byte[])imgObj;
- base64 += Convert.ToBase64String(buffer);
- this.hf_base64.Value = base64;
- // js脚本 load_obj_base64 是用来在客户端渲染图片的
- string script = "$('#lz_caption strong').text('修改楼长信息');"
- +"load_obj_base64($('#photo_lz').parent().next().children('img'),'"+ base64 + "')";
- ScriptManager.RegisterStartupScript(this, this.GetType(), "",script, true);
- }
- }
jQuery + ashx 实现图片按比例预览、异步上传及显示的更多相关文章
- 基于“formData批量上传的多种实现” 的多图片预览、上传的多种实现
前言 图片上传是web项目常见的需求,我基于之前的博客的代码(请戳:formData批量上传的多种实现)里的第三种方法实现多图片的预览.上传,并且支持三种方式添加图片到上传列表:选择图片.复制粘贴图片 ...
- 原生js实现图片预览并上传
最近主导的PC客户端网站重构工程告一段落,下一阶段开始给公司APP开发H5页面,技术栈是react.最近碰到一个需求:需要在H5页面上添加身份证照片,预览并上传.因为要兼容安卓4.4以下版本的手机,所 ...
- 用js实现预览待上传的本地图片
js实现预览待上传的本地图片,代码如下: <form name="form5" id="form5" method="post" ac ...
- 网站中集成jquery.imgareaselect实现图片的本地预览和选择截取
imgAreaSelect 是由 Michal Wojciechowski开发的一款非常好用的jquery插件,实现了图片的截取功能.其文档和Demo也是很详尽的.大家可以到http://odynie ...
- jquery+html5+canvas实现图片 预览 压缩 上传
javascirpt (function($){ $.fn.extend({ aiiUpload:function(obj) { if(typeof obj !="object") ...
- H5-FileReader实现图片预览&Ajax上传文件
图片预览 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF- ...
- 前端图片预览,上传前预览,兼容IE7、8、9、10、11,Firefox,Chrome(学习到的知识)
文章地址:http://www.cnblogs.com/rubylouvre/p/4597344.html 一.window.URL 在Chrome中,window.URL和window.webkit ...
- 如何预览将要上传的图片-使用H5的FileAPI
这篇将要说的东西已经不新鲜了. 参考资料: Reading files in JavaScript using the File APIs (鉴于作者在美国, 我姑且认为作者母语是英语, 当然链接中有 ...
- vue组件利用formdata图片预览以及上传《转载》
转载修改 在项目中直接新建一个单文件页,复制一下代码即可 upload组件: <template> <div class="vue-uploader" ...
随机推荐
- server2008r2 安装CentOS
一:安装CentOS 二:配置虚拟网络: 三:设置创建的虚拟机使用刚才创建的网卡: 四:运行CentOs,输入用户:root 密码:root,登录后输入: dhclient 自动获取IP ip ...
- [LeetCode] 200. Number of Islands 岛屿的数量
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...
- [LeetCode] 875. Koko Eating Bananas 可可吃香蕉
Koko loves to eat bananas. There are N piles of bananas, the i-th pile has piles[i] bananas. The g ...
- Java spi 和Spring spi
service provider framework是一个系统, 实现了SPI, 在系统里多个服务提供者模块可以提供一个服务的实现, 系统让客户端可以使用这些实现, 从而实现解耦. 一个service ...
- Docker创建镜像 并推拉Harbor
创建镜像 一.根据dockerfile创建镜像 文件详解 1.mkdir dockerfile/lib/centos7base/ 创建目录 2.创建Dockerfile vim Dockerfile ...
- 《Mysql - 自增主键为何不是连续的?》
一:自增主键是连续的么? - 自增主键不能保证连续递增. 二:自增值保存在哪里? - 当使用 show create table `table_name`:时,会看到 自增值,也就是 AUTO_INC ...
- Win32API文本处理
工程模板:https://www.cnblogs.com/eternalmoonbeam/p/10793080.html 安全的文本输出方式: 需要额外包含头文件strsafe.h 依次使用以下三个函 ...
- Linux 下随机启动自己的应用 -请使用while(true) 不要Console.ReadKey()
Linux 下随机启动 自己的应用 -请使用while(true) 不要Console.ReadKey() 开机启动脚本启动,某些程序无法启动 原因 例如写了一个服务,不能停止程序运行,所以主线程成不 ...
- T-SQL行列相互转换命令:PIVOT和UNPIVOT使用详解
最近在维护一个ERP 做二次开发 ,在查找数据源的时候看到前辈写的SQL ,自己能力有限 ,就在网上找找有关这几个关键字的使用方法.做出随笔以做学习之用 T-SQL语句中,PIVOT命令可以实现数据表 ...
- Qt 中的二进制兼容策略(简而言之就是地址不能变,剩下的就是让地址不变的技巧)
本文翻译自 Policies/Binary Compatibility Issues With C++ 二进制兼容的定义 如果程序从一个以前版本的库动态链接到新版本的库之后,能够继续正常运行,而不需要 ...