如何用asp.net实现文件上传的代码

如题所述

第1个回答  推荐于2016-08-14
#region 文件上传

string path = null;
string name = null;
string type2 = null;
string upfile = null;
if (fu.HasFile)
{
try
{
name = fu.FileName;
type2 = name.Substring(name.LastIndexOf(".") + 1);
upfile = System.DateTime.Now.ToString("yyyyMMddhhmmss") + "." + type2;
if (type2.ToLower() == "rar" || type2.ToLower() == "zip" || type2.ToLower() == "doc" || type2.ToLower() == "xls" || type2.ToLower() == "ppt")
{
path = Server.MapPath("file") + "\\";
if (!File.Exists(path))
{
Directory.CreateDirectory(path);
fu.SaveAs(path + name);
}
fu.SaveAs(path + name);
}
else
{
Response.Write("<script>alert('格式不正确(格式(.doc,.xls,.rar,.zip,.ppt)!');</script>");
Response.End();
}
}
catch(Exception ex)
{
Response.Write("<script>alert('上传格式错误:" + ex.Message.ToString() + "');window.location.href='Upload.aspx';</script>");
}
}
else
{
upfile = "N/A";
name="N/A";

}
if (upfile != "N/A" || name!="N/A")
{
UpLoad up = new UpLoad();
UpLoadBll uBll = new UpLoadBll();
up.setFileName(upfile);
up.setU_name(name);
if (uBll.insertFile(up))
{
Response.Write("<script>alert('" + uBll.getMsg() + "');window.location.href='Upload.aspx';</script>");
}
else
{
Response.Write("<script>alert('" + uBll.getMsg() + "');window.location.href='Upload.aspx';</script>");
}

}
else
{
Response.Write("<script>alert('上传文件的内容或上传文件不能为空!');window.location.href='Upload.aspx';</script>");

}
}
#endregion

然后把upfile 插入到数据库就OK了本回答被提问者和网友采纳
第2个回答  2014-04-01
如果是使用自带控件,那么在后台按钮事件中现需要对控件中是否有附件进行检测
如 if(FileUpload1.HasFile)
然后,使用SaveAs(文件储存虚拟路径)来保存文件就可以了。
相似回答