I have a problem, using my image uploader. It will upload all type of files.I need code behind, to sort out if it's an image (jpg, png and so on).Then it needs to save the path and filename in my sql.Saving name and path is up and running, so is the regular expression. I now need to incorporate som code that i have found here. The question is, how it's done?
My code behind is:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("~/_PublicData/Images/" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Computer_Klubben_CommunitySiteConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string strQuery = "insert into dbo.Billeder (FileName, FilePath)" + " values(@FileName, @FilePath)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("@FileName", FileName);
cmd.Parameters.AddWithValue("@FilePath", "~/_PublicData/Images/" + FileName);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
I need to put that code inside the following code, that I have found here.How can i upload only jpeg files?
我是将代码放置在此处的代码之后,还是将其放置?
请帮忙。
最佳答案
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string fileExt =
System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExt == ".jpeg" || fileExt == ".jpg")
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("~/_PublicData/Images/" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Computer_Klubben_CommunitySiteConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string strQuery = "insert into dbo.Billeder (FileName, FilePath)" + " values(@FileName, @FilePath)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("@FileName", FileName);
cmd.Parameters.AddWithValue("@FilePath", "~/_PublicData/Images/" + FileName);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
else
{
//Show Error Message. Invalid file.
}
}
}
关于c# - 仅ASP.NET文件上传图像,将路径和文件名保存在sql表中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12491608/