asp.Netファイルをアップロードし、データベースにパスを書き込む
3595 ワード
1、 ,
<asp:FileUpload ID="upFile" runat ="server" />
2、 ,
<asp:Button ID="upLoad" runat ="server" Text =" " onclick="upLoad_Click" />
3、
//
protected void upLoad_Click( object sender, EventArgs e)
{
try
{
if (upFile.PostedFile.FileName == "")
{
Response.Write( "<script>alert(' !');</script>" );
return;
}
else
{
string filePath = upFile.PostedFile.FileName;//
string fileName = filePath.Substring(filePath.LastIndexOf("\\" ) + 1);//
string fileEx = fileName.Substring(fileName.LastIndexOf("." ) + 1).ToLower();//
string serverpath = Server.MapPath( "Resources/" + theater.SelectedIndex + "/Image/" ) + fileName;//
if (fileEx == "jpg" || fileEx == "png" )
{
if (model.SelectedValue != " " )
{
upFile.PostedFile.SaveAs(serverpath);
write_DataBase( "Resources/" + theater.SelectedIndex + "/Image/" + fileName);//
}
else
{
Response.Write( "<script>alert(' !');</script>" );
}
}
else
{
Response.Write( "<script>alert(' , !');</script>" );
}
}
}
catch ( Exception ex)
{
throw ex;
}
}
4、
//
private void write_DataBase( string serverpath)
{
try
{
//
string server = ConfigurationManager .AppSettings["server" ];
string dbPath = server + serverpath;
// imageid
string sql = "select max(imageid) from image" ;
int max_imageid = 0;
OracleDataReader dr;
db.GetDateReader(sql, out dr);
if (dr.Read() && dr[0].ToString()!= "" )
{
max_imageid = Convert.ToInt32(dr[0].ToString()) + 1;// imageid id
}
// modelid
int modelid = 0;
sql = "select modelid from model where modelname = '" + model.SelectedValue + "'";
db.GetDateReader(sql, out dr);
if (dr.Read())
{
modelid = Convert.ToInt32(dr[0].ToString());
}
//
sql = "insert into image values(" + max_imageid + "," + modelid + ",'" + dbPath + "',0" + ")" ;
int return_value = 0;
db.ProcessRecord(sql, out return_value);
if (return_value == 0)
{
Response.Write( "<script>alert(' ');window.location.reload();</script>" );
}
else
{
Response.Write("<script>window.location.reload();</script>" );
}
}
catch ( Exception ex)
{
throw ex;
}
}