我目前正在使用以下代码段将数据插入数据库中的表中。它很棒。但是,我想开始添加文件名数据而不确定如何继续。
我有以下内容:
// 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;
我还有文件上传选项。但是,我不知道如何使用它来执行以下操作:
我已将正确的 enctype 添加到我的表单中,但现在有点丢失了。
有人可以解释这样做的最佳方式吗?
非常感谢您对此的任何帮助。
答案 0 :(得分:2)
要将文件存储在images文件夹中,它应该是:
FileUpload1.SaveAs(Server.MapPath("~/Images/" + FileUpload1.FileName));
然后在fileName
中添加命令参数comm.Parameters["@FileName"].Value = FileUpload1.FileName;
注意:您必须在数据库表中包含FileName
字段。
答案 1 :(得分:0)
我建议在db中存储文件。这将保证数据的一致性。
将列添加到数据库。如果图像小于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();
}