您的位置:首页 > 编程语言

小文件上传代码

2011-09-20 14:31 197 查看
前台:

<input type="file" runat="server" id="oFile" /><a runat="server" onclick="if(document.getElementById('oFile').value==''){alert('请先选择文件!');return false;}" onserverclick="Upfile_Click" href="#">上传图片</a>

后台:

protected void Upfile_Click(object sender, EventArgs e)

{

HttpPostedFile hpf = oFile.PostedFile;

if (hpf.ContentLength > 3 * 1024 * 1024)

{

MsgShow("很抱歉,上传的图片不能超过3M!");

return;

}

string extOnly="jpg|png|bmp|gif";

if (!CheckExtValid(hpf.FileName, extOnly))

{

MsgShow("文件类型限定为:" + extOnly.Replace("|", "、"));

return;

}

//设置服务器文件路径

string dFile = SiteConfig.ImgMap +"\\images\\upload\\";

Sxmobi.FileHelper.EnsureDir(dFile);

//dFile += Path.GetFileName(hpf.FileName); //原文件名

dFile += DateTime.Now.ToString("yyyyMMddHHmmssfff")+ Path.GetExtension(hpf.FileName);

hpf.SaveAs(dFile);

MsgShow("上传成功!");

}

bool CheckExtValid(string filename, string extOnly)

{

string strExt = Path.GetExtension(filename).ToUpper();

bool bOK = true;

if (extOnly != "")

{

bOK = false;

string[] arrOnly = extOnly.Split('|');

for (int i = 0; i < arrOnly.Length; i++)

{

if (strExt == "." + arrOnly[i].ToUpper())

bOK = true;

}

}

return bOK;

}

void MsgShow(string msg)

{

Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + msg + "')</script>");

}

转载请注明出处:http://blog.csdn.net/dasihg/article/details/6793656
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: