图片上传

#region 上传方法
/// <summary>
/// 上传文件,返回上传的文件的名称
/// </summary>
/// <param name="FileUpload1">上传控件的名称</param>
/// <param name="savePath">文件保存的绝对路径</param>
public static string UploadPic(ref FileUpload FileUpload1, string savePath)
{
return UploadFile(ref FileUpload1, savePath, ".rar,.jpg,.gif,.png,.txt,.doc,.wod,.exl", 1024);
}

/// <summary>
/// 上传文件,返回上传的文件的名称
/// </summary>
/// <param name="FileUpload1">上传控件的名称</param>
/// <param name="savePath">文件保存的绝对路径</param>
/// <param name="fileExts">允许上传文件的扩展名,若是多个,则之间以逗号间隔</param>
/// <param name="maxLength">文件的上限,单位为K。例如,限制最大为512K,则可直接将此参数赋值为“512”</param>
public static string UploadFile(ref FileUpload FileUpload1, string savePath, string fileExts, int maxLength)
{
string fileExt, fileName, newFileName = "0", filePath = savePath;
fileName = FileUpload1.FileName.Trim();
if (fileName.Length > 0 && FileUpload1.PostedFile.ContentLength < maxLength * 1024)
{
int j = fileName.LastIndexOf('.');
fileExt = fileName.Substring(j).ToLower();
if (fileExts.IndexOf(fileExt) > -1)
{
Random r = new Random();
int i = r.Next(0, 1000);
newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + i.ToString() + fileExt;
filePath += newFileName;
FileUpload1.SaveAs(filePath);
}
}
return newFileName;
}
#endregion 上传方法

 

 

调用

protected void Button1_Click(object sender, EventArgs e)
{
string url=TextBox2.Text;
string jpicture = "";
if (FileUpload1.FileName.Length > 3)
{

jpicture = Common.UploadPic(ref FileUpload1, Server.MapPath("~/image/"));
}
//insert into jiudian value (123,System.Web.UI.WebControls.TextBox,地址,系方,System.Web.UI.WebControls.TextBox,预订时,<p></p>2,19:28:49,)
string sql = string.Format("insert into [Image] (imagepath,url) values ('{0}','{1}')", jpicture,url);
// string sql2= "INSERT INTO [Image] "
// +"(ImagePath) "
//+" VALUES ('20120712153347443.jpg')";
if (DataBase.ExecuteNonQuery(sql) > 0)
{
Response.Write("<script type='text/javascript'>alert('添加成功!');</script>");
Response.Write("<script language=javascript>window.location.href=document.URL;</script>");
}
else
{
Response.Write("<script type='text/javascript'>alert('添加失败!');</script>");
}
}

posted on 2012-07-19 11:34  张彦山  阅读(170)  评论(0编辑  收藏  举报