function CheckFile(str)
{
var strRegex = "(.jpg|.JPG|.gif|.GIF)$"; //用于验证图片扩展名的正则表达式
var re=new RegExp(strRegex);
if (re.test(str)){
document .getElementById ("Photo").style .display ="none";
document .getElementById ("newPreview").style .display ="block";
PreviewImg(str);
return (true);
}
else{
document .getElementById ("Photo").style .display ="block";
document .getElementById ("newPreview").style .display ="none";
document .getElementById ("PhotoUpload").value="";
alert("禁止的文件扩展名");
return (false);
}
}
function PreviewImg(imgFile)
{
var newPreview = document.getElementById("newPreview");
newPreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgFile;
newPreview.style.width = "502px";
newPreview.style.height = "375px";
}
.cs
protected void PhotoUp()
{
string Oldfilename = PhotoUpload.PostedFile.FileName;
if (Oldfilename != null && Oldfilename != "" && Oldfilename.Length > 1)
{
if (PhotoUpload.PostedFile.ContentLength <= 2097152)
{
try
{
System.Drawing.Image img = System.Drawing.Image.FromStream(PhotoUpload.PostedFile.InputStream);
try
{
Oldfilename = System.IO.Path.GetFileName(Oldfilename);
int index = Oldfilename.LastIndexOf(".");
string lastName = Oldfilename.Substring(index, Oldfilename.Length - index);
if (lastName == ".JPG" || lastName == ".GIF" || lastName == ".jpg" || lastName == ".gif")
{
string filename = string.Empty;
if (HFPhotoFiles.Value.Trim() != "" && HFPhotoFiles.Value.Trim() != null)
{
filename = HFPhotoFiles.Value.Trim();
}
else
{
filename = Convert.ToString(Guid.NewGuid()) + lastName;
}
PhotoUpload.PostedFile.SaveAs(Server.MapPath("~/GroupImages/" + filename));
HFPhotoFiles.Value = filename;
}
}
catch
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('照片上传失败!')</script>");
}
}
catch
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('您上传的不是图片文件!其他信息保存成功!')</script>");
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('上传照片太大,照片应小于等于2M!')</script>");
}
}
}
.aspx
<tr>
<td height="20px" align="right">
医院照片:</td>
<td align="left" colspan =3>
<asp:FileUpload ID="PhotoUpload" runat="server" CssClass="textfield" οnchange="CheckFile(this.value);" Height="20px" Width="219px" /></td>
</tr>