JS判断上传控件是否选择正确文件,并保存到服务器
--------JS代码--------
function PreviewImage(imgFile) {
if (imgFile.value.length < 1) {
document.getElementById("imgPreview").style.filter = "";
document.getElementById("ImgPhoto").style.display = "block";
document.getElementById("ImgPhoto").src = "../Skin/Img/create.gif";
return;
}
var filextension = imgFile.value.substring(imgFile.value.lastIndexOf("."), imgFile.value.length);
filextension = filextension.toLowerCase();
if ((filextension != '.jpg') && (filextension != '.gif') && (filextension != '.jpeg') && (filextension != '.png') && (filextension != '.bmp')) {
alert("对不起,系统仅支持jpg,gif,jpeg,png,bmp格式的照片。");
imgFile.focus();
}
else {
var path;
if (document.all)//IE
{
imgFile.select();
path = document.selection.createRange().text;
document.getElementById("ImgPhoto").style.display = "none";
document.getElementById("imgPreview").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='scale',src=\"" + path + "\")";
}
else//FF
{
path = imgFile.files[0].getAsDataURL();
document.getElementById("ImgPhoto").src = path;
}
}
}
--------------Html代码----------------
<img id="ImgPhoto" height="140" alt="标题图片" onerror="document.all.BrowseTitlePicFile.select();document.execCommand('Delete');"
src="~/Skin/Img/create.gif" width="142" align="middle" name="ImgPhoto" runat="server" />
<input id="BrowseTitlePicFile" onchange="PreviewImage(this);" type="file" size="60"
name="BrowseTitlePicFile" runat="server" width="100%" />
-------------后台保存代码--------------
if (BrowseTitlePicFile.Value.ToString().Trim() != "")
{
int length = this.BrowseTitlePicFile.PostedFile.ContentLength;
Byte[] imageData = new Byte[length];
this.BrowseTitlePicFile.PostedFile.InputStream.Read(imageData, 0, length);
MemoryStream ms = new MemoryStream(imageData);
Bitmap bmp = new Bitmap(ms);
Guid guid = Guid.NewGuid();
string imageDirectory = this.Server.MapPath("~/Skin/Img/");
if (!System.IO.Directory.Exists(imageDirectory))
{
System.IO.Directory.CreateDirectory(imageDirectory);
}
string imageName = imageDirectory + fileName + ".jpg";
bmp.Save(imageName, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Close();
skin.Img = "../Skin/img/" + fileName + ".jpg";
}