当前位置: 移动技术网 > IT编程>开发语言>.net > FileUpload上传图片前实现图片预览功能(附演示动画)

FileUpload上传图片前实现图片预览功能(附演示动画)

2017年12月12日  | 移动技术网IT编程  | 我要评论
看看效果:  在专案中,创建aspx页面,拉上fileupload控件一个image,将用来预览上传时的图片。 复制代码 代码如下: view code <
看看效果:
 
在专案中,创建aspx页面,拉上fileupload控件一个image,将用来预览上传时的图片。
复制代码 代码如下:

view code
<%@ page language="c#" autoeventwireup="true" codefile="default2.aspx.cs" inherits="default2" %>
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td style="vertical-align: top; width: 10%;">
<fieldset>
<legend>选择图片</legend>
<asp:fileupload id="fileupload1" runat="server" />
</fieldset>
</td>
<td style="vertical-align: top; width: 90%;">
<fieldset>
<legend>预览</legend>
<asp:image id="image1" runat="server" visible="false" />
</fieldset>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

在page_init事件中,为fileupload控件,注册onchange客户端事件。
复制代码 代码如下:

protected void page_init(object sender, eventargs e)
{
this.fileupload1.attributes.add("onchange", page.clientscript.getpostbackeventreference(this.fileupload1, "onchange"));
}

接下来,insus.net一个axd处理文档,其实imageprocessfactory.cs只是一个普能的类别,只实作了ihttphandler接口。
复制代码 代码如下:

imageprocessfactory.cs
using system;
using system.collections.generic;
using system.drawing;
using system.drawing.drawing2d;
using system.drawing.imaging;
using system.io;
using system.linq;
using system.web;
using system.web.sessionstate;
/// <summary>
/// summary description for imageprocessfactory
/// </summary>
namespace insus.net
{
public class imageprocessfactory : ihttphandler,irequiressessionstate
{
public imageprocessfactory()
{
//
// todo: add constructor logic here
//
}
public void processrequest(httpcontext context)
{
//checking whether the uploadbytes session variable have anything else not doing anything
if ((context.session["uploadbytes"]) != null)
{
byte[] buffer = (byte[])(context.session["uploadbytes"]);
context.response.binarywrite(buffer);
}
}
public bool isreusable
{
get
{
return false;
}
}
}
}

为能能应到axd文档,需要在web.config中配置一下。
复制代码 代码如下:

view code
<configuration>
<system.web>
<httphandlers>
<add verb="*" path="previewimage.axd" type="insus.net.imageprocessfactory"/>
</httphandlers>
</system.web>
</configuration>

ok,我们回到aspx.cs页面中,要在page_load中,怎监控fileupload控件是否有值变化:
复制代码 代码如下:

view code
protected void page_load(object sender, eventargs e)
{
if (ispostback)
{
var ctrl = request.params[page.posteventsourceid];
var args = request.params[page.posteventargumentid];
onchangehandle(ctrl, args);
}
}

在page_load中有一个方法onchangehandle(xxx,xxx):
复制代码 代码如下:

view code
private void onchangehandle(string ctrl, string args)
{
if (ctrl == this.fileupload1.uniqueid && args == "onchange")
{
this.image1.visible = true;
session["uploadbytes"] = this.fileupload1.filebytes;
this.image1.imageurl = "~/previewimage.axd" ;
}
}

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网