c# - 文件上传时覆盖

标签 c# asp.net mysql sql html

嘿伙计们,有没有办法在文件上传时覆盖文件夹的任何内容,即使文件名不同?我只想在任意给定时间存储一张图像,但我无法知道用户可能上传的文件名,那么您将如何在下面的代码中覆盖它?

 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;

            }

        }
    }

}

最佳答案

当你说覆盖它时,为什么不能删除旧文件?这可以通过图像类型目录列表上的过滤器来完成,或者如果图像是其中唯一的文件,则可以通过清除整个目录来完成。

您更好的选择是从数据库中提取文件名,因为您已经存储了与用户 ID 关联的文件名。这样当用户上传新文件时,您可以调出当前用户记录并删除关联的文件,并在新文件上传完成后更新图片记录。

最后,第三种选择是将文件作为二进制值存储在数据库中。然后每次上传图片时只需将图片更新到用户图片记录中即可。

[编辑:更多详细信息]

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 注入(inject)攻击。使用 LINQ to SQL 或 Entities to SQL 之类的工具会更好。除了使从数据库读取数据和向数据库写入数据变得更加简单之外,它还提供了防止 SQL 注入(inject)的数据清理功能。

此外,每次需要时从连接字符串创建 OdbcConnection 对象是一个缓慢的过程。您可能想要创建一个延迟加载单例,它为每个 session 或应用程序实例返回一个 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.

关于c# - 文件上传时覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5432556/

相关文章:

c# - 报告服务实例的 WMI 查询返回所有实例,而不考虑父 sql server 路径

css - 带有搜索框的导航栏 - MaterializeCss

c# - 将值传递给 nlog 自定义目标

mysql-workbench - 更改 my.ini 文件不会影响 MySql 变量

c# - 环回连接在 Windows Server 2008 上不起作用

c# - C#支持多重继承吗?

c# - VS2008中.net 2.0的扩展方法

c# - 无法将类型为 'System.Web.UI.WebControls.EntityDataSourceWrapper' 的对象转换为类型

php - 时间戳、时区和夏令时

mysql - 如何在MySQL中的多个表上授予 "select"?