if(window.ActiveXObject) { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); if(typeof uri== 'boolean'){ io.src = 'javascript:false'; } else if(typeof uri== 'string'){ io.src = uri; } } else { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; } io.style.position = 'absolute'; io.style.top = '-1000px'; io.style.left = '-1000px'; document.body.appendChild(io); return io }, createUploadForm: function(id, fileElementId) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); var oldElement = $('#' + fileElementId); var newElement = $(oldElement).clone(); $(oldElement).attr('id', fileId); $(oldElement).before(newElement); $(oldElement).appendTo(form); //set attributes $(form).css('position', 'absolute'); $(form).css('top', '-1200px'); $(form).css('left', '-1200px'); $(form).appendTo('body'); return form; }, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = new Date().getTime() var form = jQuery.createUploadForm(id, s.fileElementId); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id; // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } var requestDone = false; // Create the request object var xml = {} if ( s.global ) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var uploadCallback = function(isTimeout) { var io = document.getElementById(frameId); try { if(io.contentWindow) { xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument) { xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) { jQuery.handleError(s, xml, null, e); } if ( xml || isTimeout == "timeout") { requestDone = true; var status; try { status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if ( status != "error" ) { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData( xml, s.dataType ); // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status );
// Fire the global callback if( s.global ) jQuery.event.trigger( "ajaxSuccess", [xml, s] ); } else jQuery.handleError(s, xml, status); } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if( s.global ) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); // Process result if ( s.complete ) s.complete(xml, status); jQuery(io).unbind() setTimeout(function() { try { $(io).remove(); $(form).remove();
} catch(e) { jQuery.handleError(s, xml, null, e); } }, 100) xml = null } } // Timeout checker if ( s.timeout > 0 ) { setTimeout(function(){ // Check to see if the request is still happening if( !requestDone ) uploadCallback( "timeout" ); }, s.timeout); } try { // var io = $('#' + frameId); var form = $('#' + formId); $(form).attr('action', s.url); $(form).attr('method', 'POST'); $(form).attr('target', frameId); if(form.encoding) { form.encoding = 'multipart/form-data'; } else { form.enctype = 'multipart/form-data'; } $(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } if(window.attachEvent){ document.getElementById(frameId).attachEvent('onload', uploadCallback); } else{ document.getElementById(frameId).addEventListener('load', uploadCallback, false); } return {abort: function () {}}; }, uploadHttpData: function( r, type ) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if ( type == "json" ) eval( "data = " + data ); // evaluate scripts within html if ( type == "html" ) jQuery("<div>").html(data).evalScripts(); //alert($('param', data).each(function(){alert($(this).attr('value'));})); return data; } })
这是个自定义控件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Segdzw.Business;namespace Segdzw.Business
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ImagePreview runat=server></{0}:ImagePreview>")]
public class ImagePreview : Control, INamingContainer
{
protected override void Render(HtmlTextWriter writer)
{
StringBuilder sb = new StringBuilder();
sb.Append("<div id=\""+this.ClientID+"_div\" style=\"display:none\">加载中</div> \r");
sb.Append("<input type=\"file\" id=\"" + this.ClientID + "_file\" name=\"" + this.ClientID + "_file\" onchange=\"GetPreview('"+this.ClientID+"');\"/>");
string strJs = PageUtils.GetScriptsLink(new string[] { "jquery-1.4.2.min.js", "ajaxfileupload.js", "ImagePreview.js" });
if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "ImagePreview"))
Page.ClientScript.RegisterStartupScript(this.GetType(), "ImagePreview", strJs);
writer.Write(sb.ToString());
base.Render(writer);
}
}
}
<%@ Register Assembly="Segdzw.Business" Namespace="Segdzw.Business" TagPrefix="cc1" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>上传图片</title>
</head>
<body>
<form id="form1" runat="server">
<cc1:ImagePreview ID="ImagePreview1" runat="server">
</cc1:ImagePreview>
<cc1:ImagePreview ID="ImagePreview2" runat="server">
</cc1:ImagePreview>
<cc1:ImagePreview ID="ImagePreview3" runat="server">
</cc1:ImagePreview>
</form>
</body>
</html>
$(function() // 获取浏览器的类型
{
if ($.browser.msie && ($.browser.version == "6.0") && !$.support.style)//或者用 if(document.all)
{
bwType = "ie6";
}
else if ($.browser.msie && ($.browser.version == "7.0"))
{
bwType = "ie7";
}
else if ($.browser.msie && ($.browser.version == "8.0"))
{
bwType = "ie8";
}
else if ($.browser.msie && ($.browser.version == "9.0"))
{
bwType = "ie9";
}
else
{
bwType = "not_ie";
}});
function GetPreview(clientid)
{
if (bwType == "ie6")
{
$("#"+clientid+"_div").html("<img src='" + $("#"+clientid+"_file").val() + "'>");
}
else
{
AjaxFileUpload(clientid);
}
}
function AjaxFileUpload(cid)
{
$("#" + cid + "_div").ajaxStart(function()
{
$(this).show();
})
$.ajaxFileUpload({
url: "ImagePreview.ashx",
secureuri: false,
fileElementId: cid+"_file", //Input file id
dataType: "json",
success: function(data, status)
{
if (data.status == "success")
{
$("#" + cid + "_div").html("<img src='data:image/gif;base64," + data.msg + "'>");
}
},
error: function(data, status, e)
{
alert(data + status + e);
} });
}
ImagePreview.ashx:
<%@ WebHandler Language="c#" Class="File_WebHandler" Debug="true" %>using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;public class File_WebHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
HttpPostedFile file = context.Request.Files[0];
string path="";
if (file.ContentLength > 0 && file.ContentType.IndexOf("image/") >= 0)
{
int width = 200;
int height = 200;
try
{
path = @"{status: 'success',msg: '" + Convert.ToBase64String(ResizeImg(file.InputStream, width, height).GetBuffer()) + @"'}";
}
catch (Exception)
{ path = @"{status: 'error',msg: '发生错误'}";
}
context.Response.Write(path);
}
}
} public MemoryStream ResizeImg(Stream ImgFile, int maxWidth, int maxHeight)
{
Image imgPhoto = Image.FromStream(ImgFile);
decimal desiredRatio = Math.Min((decimal)maxWidth / imgPhoto.Width, (decimal)maxHeight / imgPhoto.Height);
int iWidth = (int)(imgPhoto.Width * desiredRatio);
int iHeight = (int)(imgPhoto.Height * desiredRatio);
Bitmap bmPhoto = new Bitmap(iWidth, iHeight); Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
gbmPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
gbmPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gbmPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(0, 0, imgPhoto.Width, imgPhoto.Height), GraphicsUnit.Pixel); MemoryStream ms = new MemoryStream();
bmPhoto.Save(ms, ImageFormat.Jpeg); imgPhoto.Dispose();
gbmPhoto.Dispose();
bmPhoto.Dispose(); return ms;
} public bool IsReusable
{
get
{
return false;
}
}
}
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px'; document.body.appendChild(io); return io
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
}, ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
} // The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" ); // Process result
if ( s.complete )
s.complete(xml, status); jQuery(io).unbind() setTimeout(function()
{ try
{
$(io).remove();
$(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
} }, 100) xml = null }
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}}; }, uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
})