<asp:FileUpload ID="fuPhoto" runat="server" name="fuPhoto" οnchange="setImagePreview(this);" />
<img id="preView" alt="" src="<%=StyleUrl %>images/none.jpg" class="thumbImage xzyy">
<div id="div_view" style="height: 6px; width: 6px">
<asp:ImageButton ID="btnSave" OnClick="btnSave_Click" OnClientClick="return VaillReturn()"
runat="server" ImageUrl="http://artvillageonline.com/Template/xpshop_clothes2/images/Step1images/submit.jpg" />
<pre name="code" class="html">OnClientClick为JS验证
function setImagePreview(obj) {
var docObj = obj;
var imgObjPreview = document.getElementById("preView");
if (docObj.files && docObj.files[0]) {
var file = docObj.files[0];
if (!checkCondition(file.name)) {
clearLogo();
return;
}
if ('FileReader' in window) {
var reader = new FileReader();
reader.onload = function(e) {
imgObjPreview.setAttribute("src", e.target.result);
}
reader.readAsDataURL(docObj.files[0]);
}
else
imgObjPreview.src = window.URL.createObjectURL(file);
//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
//imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
}
else {
//IE下,使用滤镜
var localImagId = document.getElementById("div_view");
docObj.select();
localImagId.focus();
var imgSrc = document.selection.createRange().text;
if (!checkCondition(imgSrc)) {
clearLogo();
return;
}
imgObjPreview.style.width = "300px";
imgObjPreview.style.height = "300px";
//图片异常的捕捉,防止用户修改后缀来伪造图片
try {
imgObjPreview.src = "";
imgObjPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
imgObjPreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
} catch (e) {
alert("您上传的图片格式不正确,请重新选择!");
return false;
}
imgObjPreview.style.backgroundColor = "#ffffff";
document.selection.empty();
}
if ($("#txtLength").val() != "" && $("#txtLength").val() != "0") {
if ($("#CheckSize").is(':checked')) {
var image = new Image();
image.src = imgObjPreview.src;
HeightorWidth(image.height, image.width);
}
} else {
$("#CheckSize").attr("checked", false); //重置
}
return true;
}
function checkCondition(name) {
var limitSize = 200 * 1024;
if (!/.(gif|jpg|jpeg|png)$/.test(name)) {
alert("Can only upload the GIF | JPG | jpeg | PNG format images");
return false;
}
return true;
}
protected void btnSave_Click(object sender, System.EventArgs e)
{
try
{
string ext = System.IO.Path.GetExtension(fuPhoto.PostedFile.FileName).ToLower();
string filename = "product_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ext;
string path = "~/UploadPhoto/" + filename;
if (!Directory.Exists(this.Server.MapPath("~/UploadPhoto/")))
{
Directory.CreateDirectory(this.Server.MapPath("~/UploadPhoto/"));
}
fuPhoto.PostedFile.SaveAs(Server.MapPath(path));
}
}