//判断上传文件是否是图片
private static bool IsAllowedExtension(FileUpload upfile)
{
string strOldFilePath = "";
string strExtension = "";
string[] arrExtension = { ".gif", ".jpg", ".bmp", ".png" };
if (upfile.PostedFile.FileName != string.Empty)
{
strOldFilePath = upfile.PostedFile.FileName;//获得文件的完整路径名
strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));//获得文件的扩展名,如:.jpg
for (int i = 0; i < arrExtension.Length; i++)
{
if (strExtension.Equals(arrExtension[i]))
{
return true;
}
}
}
return false;
}
//图片上传并将图片重命名
protected void FileUpload_Button_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.HasFile)
{
if (IsAllowedExtension(FileUpload1))
{
string filepath = FileUpload1.FileName;
//string filename = filepath.Substring(filepath.LastIndexOf('\\') + 1, filepath.Length - filepath.LastIndexOf('\\') - 1);//(filepath.LastIndexOf("\\") + 1);
//以年-月-日-时-分-秒-毫米将图片重新命名
string filename = DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fffffff")+filepath.Substring(filepath.LastIndexOf('.'), filepath.Length - filepath.LastIndexOf('.'));
//设定上传路径(绝对路径)
string uppath = Server.MapPath("~/Photo/") + filename;
//图片上传至绝对路径
FileUpload1.PostedFile.SaveAs(uppath);
//设定数据库的存储路径
string savepath="~\\Photo\\"+filename;
HiddenField1.Value = savepath;
lblInfo.Text = "上传成功!";
}
}
else
{
lblInfo.Text = "请选择上传文件";
}
}
catch (Exception ex)
{
lblInfo.Text = "上传发生错误!原因是:" + ex.ToString();
}
}
前台放三个控件
前台代码:
<asp:FileUpload ID="FileUpload1" runat="server" Font-Size="13px" BorderColor="Gray" BorderStyle="Solid" BorderWidth="1px" Height="25px" Width="400px" />
<asp:Button ID="FileUpload_Button" runat="server" Text="上传图片" Height="25px"
CausesValidation="False" onclick="FileUpload_Button_Click" />
<asp:Label id="lblInfo" runat="server" ForeColor="Red" Font-Size="13px" ></asp:Label>
注:
1、FileUpload 控件不能放在UpdatePanel控件内,如果放在UpdatePanel内FileUpload1.HasFile始终为false
2、在给insert语句填充数据时,要使用cmd.Parameters.AddWithValue("@b", savepath);的格式防止字符串savepath中的'\'转义,若使用string sql=string.Format("insert into table1(path) values('{0}')",savepath);的格式,存入数据库的图片路径将会没有'\'。
3、若在图片上传的页面中有验证控件,且不想在单击图片上传按钮的过程中进行验证,需要加上CausesValidation="False"属性。
更多图片上传问题参考:http://leonardleonard.iteye.com/blog/276213
本文详细介绍了一种在ASP.NET中实现图片上传的方法,包括如何判断上传文件是否为图片格式,如何将图片重命名并保存至指定路径,以及在数据库中正确存储图片路径的技巧。此外,还提供了关于FileUpload控件使用的注意事项,以及如何避免在图片上传过程中出现的常见问题。
3998

被折叠的 条评论
为什么被折叠?



