asp.net预览图片

Aspx code

<table>

        <tr>

            <td class="style3">

                <asp:Label ID="Label1" runat="server" Text="Photo upload" />

            </td>

            <td class="style4">

                <asp:FileUpload runat="server" ID="PhotoUpload" />

            </td>

            <td class="style4">

                <asp:Button runat="server" ID="btnPhotoPreview" Text="Preview" />

            </td>

            <td class="style1">

                <asp:Image runat="server" ID="ImagePreview" Height="164px" Width="125px" />

            </td>

        </tr>

    </table>

 

2.添加一个ID为btnPhotopreview的Button按钮

<asp:Button runat="server" OnClick="btnPreview_Click" ID="btnPhotoPreview" Text="Preview" />

3

.添加一个 .ashx文件,ashx是什么文件?

.ashx 文件用于写web handler的。.ashx文件与.aspx文件类似,可以通过它来调用HttpHandler类,它免去了普通.aspx页面的控件解析以及页面处理的过程。其实就是带HTML和C#的混合文件。
.ashx文件适合产生供浏览器处理的、不需要回发处理的数据格式,例如用于生成动态图片动态文本等内容。
<%@ WebHandler Language="C#" Class="ImageHandler" %>
 
using System;
using System.Web;
 
public class ImageHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
   
    public void ProcessRequest (HttpContext context) {
       //Checking whether the imagebytes session variable have anything else not doing anything
 
        if ((context.Session["ImageBytes"]) != null)
        {
            byte[] image = (byte[])(context.Session["ImageBytes"]);
            context.Response.ContentType = "image/JPEG";
            context.Response.BinaryWrite(image);
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
 
}

4.双击button按钮注册事件。

protected void btnPreview_Click(object sender, EventArgs e)

    {

        Session["ImageBytes"] = PhotoUpload.FileBytes;

        ImagePreview.ImageUrl = "~/ImageHandler.ashx";

    }

 参考:

http://www.c-sharpcorner.com/uploadfile/1a81c5/previewing-image-in-asp-net-image-control/

 

原文地址:https://www.cnblogs.com/code-charmer/p/4046317.html