js实现FileUpload选择图片后预览功能

时间:2024-01-15 23:46:38

当asp.net的FileUpload选择一个图片后不需要上传就能显示出图片的预览功能,

代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function selected(obj) {
var str = "carpoolpic";
str = str + obj.value;
var imgSrc = document.getElementById(str).value;
if (imgSrc == "" || imgSrc == null) {
alert("此项没有图片");
obj.checked = false;
}
changesrc(str);
} var flag = true;
function changesrc(sender) {
if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
var imgSrc = document.getElementById(sender).value;
var t = document.getElementById(sender);
if (imgSrc == "") {
flag = false;
return false;
}
if (/(.*?)\.jpg$/.test(imgSrc.toLowerCase()) == false) {
document.getElementById(sender).value = "";
alert("只能选择jpg格式!");
flag = false;
return false;
} else {
var imgs = document.createElement("img");
imgs.src = imgSrc; if (imgs.fileSize > 50 * 1024) {
alert("图片大小不能超过 50 KB!");
flag = false;
return false;
}
flag = true;
}
document.getElementById("upImg").src = window.URL.createObjectURL(t.files[0]);
} else {
document.getElementById(sender).select();
var imgSrc = document.selection.createRange().text;
if (imgSrc == "") {
flag = false;
return false;
}
if (/(.*?)\.jpg$/.test(imgSrc.toLowerCase()) == false) {
document.getElementById(sender).value = "";
alert("只能选择jpg格式!");
flag = false;
return false;
} else {
var imgs = document.createElement("img");
imgs.src = imgSrc;
flag = true;
}
document.getElementById("upImg").src = imgSrc;
}
} function checkpic() {
var raFlag = false;
var obj = document.getElementsByName("select");
for (var i = 0; i < obj.length; i++) {
if (obj[i].checked) {
raFlag = true;
break;
} else {
raFlag = false;
}
}
if (raFlag == false && flag == true) {
alert("请选择最新的照片");
}
var subFlag = false;
subFlage = flag && raFlag;
flag = false;
return subFlage;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div> <asp:FileUpload ID="fupweb_image" runat="server" class="chenck_upload left" onchange="changesrc(this.id)" /></span>
<img id="upImg" runat="server" src=" " /> </div>
</form>
</body>
</html>