string reason = "";
string filename = "";
try
{
if (FileAlbImage.FileName != "")
{
bool filetf = FileUp(this.Page, FileAlbImage, new string[] { ".jpg", ".gif", ".png" }, 2 * 1024 * 1024, "D+F", "../AlbumImages/", out reason, out filename);
if (!filetf)
{
Page.RegisterStartupScript("", "<script>alert('上传图片失败,请重新上传!');document.location='../User/AlbumInsert.aspx';</script>");
}
}
}
catch (Exception)
{
Page.RegisterStartupScript("", "<script>alert('上传图片失败,请重新上传!');document.location='../User/AlbumInsert.aspx';</script>");
throw;
}
if (FileAlbImage.FileName == "")
{
albums.AlbImage = "../AlbumImages/" + "2010041901443434.jpg";//放张默认照片吧 控件FileUpload的IDFileAlbImage
}
else
{
albums.AlbImage = "../AlbumImages/" + filename;//albums是实体类
}
bool result = album.InsertZGTYAlbum(albums);//添加到数据库
if (result == true)
{
Response.Redirect("AlbumTitle.aspx");
}
上传照片
FileUp方法
/// <summary>
/// 配合FileUpload控件使用的通用上传方法
/// </summary>
/// <param name="page">需要上传的页面</param>
/// <param name="fileProduct">需要上传的FileUpload控件</param>
/// <param name="allType">上传文件的格式限制</param>
/// <param name="filesize">上传文件的大小限制</param>
/// <param name="type">文件命名的规则类型 由D,D+F,F D:表示根据时间命名,F:表示根据文件名命名,D+F:表示根据时间+文件名</param>
/// <param name="path">文件保存的路径</param>
/// <param name="reason">如果发生错误则返回处理过程中产生的错误原因,无发生错误则返回上传成功</param>
/// <param name="filename">如果上传成功,则将返回文件名称</param>
/// <returns>是否上传成功</returns>
public static bool FileUp(Page page, FileUpload fileProduct, string[] allType, int filesize, string type, string path, out string reason, out string filename)
{
filename = "";
if (!fileProduct.HasFile)
{
reason = "该路径并不是文件,请重新上传";
return false;
}
string fileExtension = System.IO.Path.GetExtension(fileProduct.FileName).ToLower();
bool flag = false;
foreach (string str in allType)
{
if (fileExtension == str)
{
flag = true;
}
}
if (!flag)
{
reason = "文件的格式有错误,请选择符合的格式";
return false;
}
if (fileProduct.PostedFile.ContentLength > filesize)
{
reason = "文件大小过大,请选择符合的大小";
return false;
}
string url = null;
switch (type)
{
case "D+F":
url = DateTime.Now.ToString("yyyyMMddhhmmss") + fileProduct.FileName;
fileProduct.SaveAs(page.Server.MapPath(path) + url);
break;
case "F":
url = fileProduct.FileName;
fileProduct.SaveAs(page.Server.MapPath(path) + url);
break;
case "D":
url = DateTime.Now.ToString("yyyyMMddhhmmss") + fileExtension;
fileProduct.SaveAs(page.Server.MapPath(path) + url);
break;
}
reason = "上传成功";
filename = url;
return true;
}