上传图片生成缩略图
asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnaddd" runat="server" Text="上传" OnClick="btnaddd_Click" />
<div id="zyc"></div>
<asp:Label ID="lb" runat="server" Text="" ForeColor="red"></asp:Label>
function AddFileUpLoad(Str)
{
var oDiv=document.getElementById("zyc");
oDiv.style.visibility="visible";
oDiv.innerHTML="<img src=\""+document.getElementById(Str).value+"\">";
// oDiv.innerHTML=document.getElementById(Str).value;;
}
</script>
cs代码:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.FileUpload1.Attributes.Add("onchange", "AddFileUpLoad('" + this.FileUpload1.ClientID + "')");
}
//txttime.Text = DateTime.Now.ToString("yyyy-MM-dd");
}
protected void btnaddd_Click(object sender, EventArgs e)
{
//图片上传
if (FileUpload1.PostedFile.ContentLength > 1024 * 1024 * 2)
{
lb.Text = "上传的图片不能超过 2 M";
return;
}
string filepath = "";
string filename = "";
if (FileUpload1.PostedFile.ContentLength != 0)
{
filepath = Server.MapPath("../upfile/" + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(FileUpload1.PostedFile.FileName));
if (FileUpload1.PostedFile.ContentType.Equals("image/gif") || FileUpload1.PostedFile.ContentType.Equals("image/pjpeg") || FileUpload1.PostedFile.ContentType.Equals("image/JPG"))
{
if (FileUpload1.PostedFile != null)
try
{
FileUpload1.PostedFile.SaveAs(filepath);
}
catch (Exception exc)
{
lb.Text = "保存文件时出错<b>" + filepath + "</b><br>" + exc.ToString();
return;
}
filename = "upfile/" + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(FileUpload1.PostedFile.FileName);
}
else
{
lb.Text = "请上传JPG格式、GIF格式或JPG格式的图片!";
return;
}
}
else {
lb.Text = "请上传图片!";
return;
}
}