Upload image to server using C#/.NET and storing filename in DB

♀尐吖头ヾ 提交于 2019-12-01 22:44:58

问题


I'm currently using the following snippet to insert data into a table in my database. It works great. But, I want to start adding filename data and not sure how to proceed.

I have the following:

// 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;

I also have a File Upload option. But, I don't know how to use this to do the following:

  • move the file to my images directory and
  • store the filename value in my table.

I have added the correct enctype to my form but now a little lost.

Can someone explain the best way to do this?

Many thanks for any help with this.


回答1:


To store the file in an images folder, it should be:

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

and then add the command parameters in the fileName

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

Note: you must have the FileName field in your DB table.




回答2:


I suggest storing file in the db too. This will guarantee data consistency.

Add column to the DB. Replace X with the suitable size if the image is less than 8000, or specify varbinary(MAX) if it is not.

alter table Entries
    add FileContent varbinary(X) not null

C# code:

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();
}


来源:https://stackoverflow.com/questions/6054359/upload-image-to-server-using-c-net-and-storing-filename-in-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!