using System.Data;
using System.Data.SqlClient;
using configuration;
using System.IO;
//将数据添加到数据库,然后将照片传到相应文件夹中
//在项目中新建文件夹用于存放加载的图片 MyFile
static string connStr=ConfigurationManager.AppSettings("ConnStr");
SqlConnection conn=new SqlConnection(connStr);
protected viod Page_Load(object sender ,EventArgs e)
{
BindPhoto();
}
void BindPhoto()
{
string sql ="select * from PhotoInfo";
SqlDataAdapter da=new SqlDataAdapter(sql,conn);
DataSet ds=new DataSet();
da.Fill(ds); // 填充到ds
GridView1.DataSource=ds.Table[0];
GridView1.DataBind();
}
protection void Button_Click(Object sender ,EventArgs e)
{
//获取文件名称
string myFileName= FileUpload1.FileName;
//获取文件夹路径
string myFullFileName=FileUpload1.PostedFile.FileName;
//获取路径的后缀并转换成小写
string mySuffix=Path.GetExtention(myFullFileName).ToLower();
//判断后缀名是否是图片格式
if(mySuffix==".jpg"||mySuffix==".gif"||mySuffix==".bmp"||mySuffix==".jpeg")
{
//获取图片大小
int imgLength=FileUpload1.PostedFile.ContentLength;
if((imgLength/1024)<1024)
{
//添加到数据库
string sql="insert into PhotoInfo(PhotoTitle,PhotoName,PhotoDes)values(' "+txtTitle.Text+" ', ' "+myFileName +" ', ' "+txtDes.Text+" ');
SqlCommand cmd=new SqlCommand(sql,conn);
conn.Open();
int i=cmd.ExecuteNonQuery();
conn.Close();
if(i>0)
{
string upload=Server.GetMap("MyFile\\"+myFileName); // 获取要上传到的文件夹相对路径
FileUpload1.SaveAs(upload); //保存
Response.Write("上传成功") ;
}
else
{
Response.Write("图片上传未成功") ;
}
}
else
{
Response.Write("上传图片太大");
}
}
else
{
Response.Write("图片格式不符");
}
}
//修改web.config 上传图片大小等 ,在web.config中添加httpRuntime元素,如下
<configuration>
<system.web>
<httpRuntime maxRequestLength=8192
useFullQualifiedRedirectUrl=true
executionTimeout=45
versionHeader=.1.2.4128/>
</system.web>
</configuration>
//在winform中获取相对路径和在web中
string dir=Direction.GetCurrentDirection;
string dir=Server.GetMap("文件名称");
本文介绍如何使用ASP.NET实现图片上传功能,并将其保存至指定文件夹,同时记录图片信息到数据库,最后在网页上展示所有已上传的图片。

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



