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

前端 未结 2 576
小蘑菇
小蘑菇 2021-01-19 19:06

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.

相关标签:
2条回答
  • 2021-01-19 19:37

    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.

    0 讨论(0)
  • 2021-01-19 19:39

    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();
    }
    
    0 讨论(0)
提交回复
热议问题