【问题标题】:Upload image to server using C#/.NET and storing filename in DB使用 C#/.NET 将图像上传到服务器并将文件名存储在数据库中
【发布时间】:2011-08-28 14:27:19
【问题描述】:

我目前正在使用以下 sn-p 将数据插入数据库中的表中。它工作得很好。但是,我想开始添加文件名数据,但不知道如何继续。

我有以下几点:

// Create command 
comm = new SqlCommand(
  "INSERT INTO Entries (Title, Description) " +
  "VALUES (@Title, @Description)", conn);

// Add command parameters
comm.Parameters.Add("@Description", System.Data.SqlDbType.Text);
comm.Parameters["@Description"].Value = descriptionTextBox.Text;
comm.Parameters.Add("@Title", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["@Title"].Value = titleTextBox.Text;

我还有一个文件上传选项。但是,我不知道如何使用它来执行以下操作:

  • 将文件移动到我的images目录和
  • filename 值存储在我的表中。

我已将正确的 enctype 添加到表单中,但现在有点丢失。

有人能解释一下最好的方法吗?

非常感谢您对此提供的任何帮助。

【问题讨论】:

标签: asp.net sql sql-server image upload


【解决方案1】:

要将文件存储在图像文件夹中,它应该是:

FileUpload1.SaveAs(Server.MapPath("~/Images/" + FileUpload1.FileName));

然后在文件名中添加命令参数

comm.Parameters["@FileName"].Value = FileUpload1.FileName;

注意:您的 DB 表中必须有 FileName 字段。

【讨论】:

  • 太棒了!!!这对我来说看起来不错。我现在不在代码附近,但会在今天晚些时候。我会让你知道我是怎么过的。非常感谢:D
  • 当您尝试上传另一个具有相同文件名的文件时会发生什么? :) 应该将原始文件名存储在数据库中,但使用随机 guid 或内容哈希之类的东西将其存储在服务器文件系统上。
  • 是的,如果您将原始文件名存储在数据库中并使用GUID将其存储在文件系统中会更好。
  • 嗨。我正在尝试这个,但不幸的是得到了错误"CS1061: 'System.Web.UI.HtmlControls.HtmlInputFile' does not contain a definition for 'SaveAs' and no extension method 'SaveAs' accepting a first argument of type 'System.Web.UI.HtmlControls.HtmlInputFile' could be found (are you missing a using directive or an assembly reference?) 有什么想法吗?
  • 我的表单是:<form runat="server" enctype="multipart/form-data"> 并且有 <input id="filUpload" type="file" name="filUpload" runat="server">。我的代码隐藏文件包括:filUpload.SaveAs(Server.MapPath("~/Images/" + filUpload.FileName));comm.Parameters["@FileName"].Value = filUpload.FileName;——希望这很有用。非常感谢。
【解决方案2】:

我建议也将文件存储在数据库中。这将保证数据的一致性。

将列添加到数据库。如果图像小于 8000,则将 X 替换为合适的大小,否则指定 varbinary(MAX)。

alter table Entries
    add FileContent varbinary(X) not null

C#代码:

byte[] fileContent = yourFileContent;
using(var connection = new SqlConnection(connectionString))
using (var command = connection.CreateCommand())
{
    command.CommandText = @"
        INSERT INTO Entries (Title, Description, FileContent)
        VALUES (@Title, @Description, @FileContent)
        ";
    command.Parameters.AddWithValue("Description", descriptionTextBox.Text);
    command.Parameters.AddWithValue("Title", titleTextBox.Text);
    command.Parameters.AddWithValue("FileContent", fileContent);
    connection.Open();
    command.ExecuteScalar();
}

【讨论】:

  • 好声音。我通常有点厌倦将文件数据直接添加到数据库中,但会看看这个。感谢您如此及时的回复。
猜你喜欢
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
  • 2020-01-28
  • 2015-03-02
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多