以下是本在网站找的源码,希望对大家有点帮助:


protected void btnAdd_Click(object sender, EventArgs e)//上传事件
{
bool fileOK = false;
string path = Server.MapPath("~/images/productPic/");//上传到服务器上的指定路径
if (FileUpload1.HasFile)//如果有上传文件,则判断文件类型
{
String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
String[] allowedExtensions = { ".gif", ".png", ".bmp", ".jpg" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
string timeStr = Convert.ToString(DateTime.Now.Year) + Convert.ToString(DateTime.Now.Month) + Convert.ToString(DateTime.Now.Day) + Convert.ToString(DateTime.Now.Hour) + Convert.ToString(DateTime.Now.Minute) + Convert.ToString(DateTime.Now.Second);//可以自己改,用于改变上传图片名称
FileUpload1.SaveAs(path + timeStr + FileUpload1.FileName);//将文件保存
//调用保存商品信息的方法,里面有一个参数是将商品图片路径保存到指定定段
bool succeed = cb.GoodsAdd_AddOneGood(this.txtGoodsName, this.txtGoodsType, this.txtGoodsAddress, "images/productPic/" + timeStr + FileUpload1.FileName, this.txt_Confine, this.txtGoodsColor, this.txtGoodsPrice, this.txtGoodsMaterial, this.txtGoodsModel, DateTime.Now);
if (succeed)
{
Response.Write("<script>alert('商品添加成功!')</script>");
}
else
{
Response.Write("<script>alert('商品添加失败!')</script>");
}
//这些注释了的语句在某些情况下可能会有用的。。
// LabMessage1.Text = "文件上传成功.";
// LabMessage2.Text = "<b>原文件路径:</b>" + FileUpload1.PostedFile.FileName + "<br />" +
// "<b>文件大小:</b>" + FileUpload1.PostedFile.ContentLength + "字节<br />" +
//"<b>文件类型:</b>" + FileUpload1.PostedFile.ContentType + "<br />";
}
catch (Exception ex)
{
// LabMessage1.Text = "文件上传不成功.";
Response.Write(cc.MessageBox("文件上传不成功"));
}
}
else
{
//LabMessage1.Text = "只能够上传图片文件.";
Response.Write(cc.MessageBox("只能够上传图片文件"));
}
}