看看效果:
在專案中,創建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" ;
}
}
您可能感興趣的文章:- 基于jquery實現的上傳圖片及圖片大小驗證、圖片預覽效果代碼
- 上傳圖片預覽JS腳本 Input file圖片預覽的實現示例
- js實現上傳圖片預覽的方法
- js 上傳圖片預覽問題
- javascript IE7 瀏覽器本地圖片預覽
- 純JS實現的批量圖片預覽加載功能
- JavaScript 圖片預覽效果 推薦
- 兼容最新firefox、chrome和IE的javascript圖片預覽實現代碼
- 手機圖片預覽插件photoswipe.js使用總結
- 移動端點擊圖片放大特效PhotoSwipe.js插件實現