if (FileUploadControl.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=x; Password=x;");
cn.Open();
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/")+Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/"+theUserId+"/uploadedimage/")+filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('"+theUserId+"','"+fileuploadpaths+"')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
答案 0 :(得分:1)
当你说覆盖它时,你为什么不能删除旧文件?这可以通过类型图像的目录列表上的过滤器来完成,或者如果图像是其中唯一的文件则通过清除完整目录来完成。
您更好的选择是从数据库中提取文件名,因为您已经存储了与userID关联的文件名。这样,当用户上传新文件时,您可以调用当前用户记录并删除相关文件,并在上传新文件后完成更新图片记录。
最后,第三个选项是将文件作为二进制值存储在数据库中。然后,每次上传图像时,只需将图像更新为用户图片记录。
[编辑:更多详情]
if (FileUploadControl.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=x; Password=x;");
cn.Open();
//
//Something like this
//
OdbcCommand sc = new OdbcCommand(string.format("SELECT picturepath FROM Pictures WHERE UserID ='{0}'", theUserId), cn);
OdbcDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (System.IO.File.Exists(reader[0]))
{
System.IO.File.Delete(reader[0]);
}
}
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/")+Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/"+theUserId+"/uploadedimage/")+filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('"+theUserId+"','"+fileuploadpaths+"')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
但是,我必须警告你。使用这样的代码是非常草率和不安全的。例如,在代码中使用sql查询字符串会打开您的站点以进行SQL注入攻击。你最好使用LINQ to SQL或Entities to SQL之类的东西。除了使数据更容易读取和写入数据库之外,它还提供了防止SQL注入的数据卫生。
每次需要时也从连接字符串创建OdbcConnection对象是一个缓慢的过程。您可能希望创建一个延迟加载单例,它返回每个会话或应用程序实例的OdbcConnection的单个实例。
然后,如果由于某种原因你想要创建OdbcConnection对象的单个实例,你可能想要查看using函数。
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=x; Password=x;"))
{
// DO some Work here with the OdbcConnection
} // Automatically close and dispose of the connection object to avoid memory leaks.