Asp.net 上传图片,保存路径到数据库

时间:2022-11-28 19:01:16

    本方法相对独立,直接放到页面中,调用即可,返回上传后图片的路径,图片名称已经修改为纯数字+后缀名

    /// <summary>
/// 上传文件,返回保存的路径/文件名
/// </summary>
/// <param name="fupload">web控件</param>
/// <param name="Folder">文件夹路径</param>
/// <returns></returns>
private string UploadFile(FileUpload fupload, string Folder)
{
string strNewUrl = "";
string strFileOldName = "";
string strFileNewName = "";

strFileOldName = fupload.FileName;
if (strFileOldName.Trim().Length == 0)
{
return "";
}
string fileType = strFileOldName.Substring(strFileOldName.LastIndexOf('.'));
if (fileType.ToUpper() != ".JPG" && fileType.ToUpper() != ".GIF" && fileType.ToUpper() != ".PNG" && fileType.ToUpper() != ".JPEG")//此处可换成其他的,判断限制上传文件的格式。
{
Common.MessageBoxCancel(this.Page, "请选择正确图片格式(JPG、GIF、PNG、JPEG)!", HttpContext.Current.Request.Url.ToString());
return "";
}

strFileNewName = Common.GetNo() + fileType;

try
{
string newPath = Folder;
if (!Directory.Exists(HttpContext.Current.Server.MapPath(newPath)))
{
//HttpContext.Current.Server.MapPath(相对路径):把相对路径转为服务器上的绝对路径。
//File.Exists(绝对路径):检查是否存在绝对路径指向的文件或目录。
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(newPath));
//System.IO.Directory.CreateDirectory(文件夹绝对路径):建立绝对路径文件夹。
}
strNewUrl = newPath + strFileNewName;
//上传文件并指定上传目录的路径
fupload.PostedFile.SaveAs(Server.MapPath(newPath) + strFileNewName);
return strNewUrl;
}
catch (Exception ex)
{
return strNewUrl = "出现异常,无法上传!" + ex.Message;
}
}