上传图片文件并显示
<asp:Label ID="Label9" runat="server" Text="图片:"></asp:Label> <br />
<div id="localImag" style="width: 300px; height: 200px; margin-left:250px">
<font face="微软雅黑" size="-1">
<% LXmallDBDataContext context = new LXmallDBDataContext();
string listcode = Request["ids"].ToString();
string data = context.Goods_Type.Where(p => p.ListCode == listcode).First().Pic; %> <img id="preview" alt="请先点击选择要上传的图片" src="<%=data %>" style="width:300px; height:200px" >
</font>
<asp:FileUpload ID="PicLoad" style="position:relative; top:-207px; opacity:0; left: -6px; height: 205px; text-align: right; width: 327px;" runat="server" onchange="javascript:setImagePreview(this,localImag,preview);">
</asp:FileUpload>
</div>
<script type="text/javascript">
function setImagePreview(docObj, localImagId, imgObjPreview)
{
if (docObj.files && docObj.files[0])
{
//火狐下,直接设img属性
imgObjPreview.style.display = 'block';
imgObjPreview.style.width = '300px';
imgObjPreview.style.height = '200px';
//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
}
else {
//IE下,使用滤镜
docObj.select();
var imgSrc = document.selection.createRange().text;
//必须设置初始大小
localImagId.style.width = "300px";
localImagId.style.height = "200px";
//图片异常的捕捉,防止用户修改后缀来伪造图片
try {
localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
}
catch (e) {
alert("您上传的图片格式不正确,请重新选择!");
return false;
}
imgObjPreview.style.display = 'none';
document.selection.empty();
}
return true;
}
</script>
<br />
<br />
<br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="确认" /> <br /> <br />
后台代码:
//修改内容
string listcode = Request["ids"].ToString();
Goods_Type data = context.Goods_Type.Where(p => p.ListCode == listcode).First();
if (PicLoad.HasFile) //这个空间里面有没有文件
{
string lujing = data.Pic; //删除图片 File.Delete(Server.MapPath(lujing));
//1.找到要上传的文件名
string name = PicLoad.FileName.ToString();
//2.处理文件名 ,防止上传的文件名被覆盖,
string clname = DateTime.Now.ToString("yyyyMMddhhmmssms") + name;
//3.造一个要保存的路径
string path = @"Images\" + clname;
//处理相对路径为相对路径。是一个映射
string jdpath = Server.MapPath(path);
//5,保存
PicLoad.SaveAs(jdpath);
data.Pic = "Images/" + clname;
}