ASP.NET Store uploaded sql server table file

How to save a file that was uploaded by ASP.net web form to the varbinary (max) field of sql server?

Here is what I still have:

protected void btnUpload_Click(object sender, EventArgs e)
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        StoreFile(Request.Files[i]);
    }
}

private void StoreFile(HttpPostedFile file)
{
    // what do i do now?
}

A typical ado.net example would be nice. So there is an linq example to sql.

thanks

+3
source share
4 answers

There's a good tutorial on how to upload a file directly to the database at 4GuysFromRolla

+3
source

Here's how I did it using Linq To Sql:

FilesDataContext db = new FilesDataContext();

protected void btnUpload_Click(object sender, EventArgs e)
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        StoreFile(Request.Files[i]);
    }

    db.SubmitChanges();
}

private void StoreFile(HttpPostedFile file)
{
    byte[] data = new byte[file.ContentLength];
    file.InputStream.Read(data, 0, file.ContentLength);

    File f = new File();
    f.Data = data;
    f.Filename = file.FileName;
    db.Files.InsertOnSubmit(f);
}
+2
source

This is usually considered a bad form. This inflates your database and actually does not give any advantages compared to storing all the files in a folder with a hard drive and just storing the file location in the database. Do you really want to do this?

+1
source

Here, Ronnie's quick refactor answers:

Public Shared Sub SaveUploadedFile(File As HttpPostedFile)
  Dim oFile As Db.File

  oFile = New Db.File
  oFile.Data = File.ToBytes
End Sub

<Extension()>
Public Function ToBytes(File As HttpPostedFile) As Byte()
  ToBytes = New Byte(File.ContentLength - 1) {}

  Using oStream As Stream = File.InputStream
    oStream.Read(ToBytes, 0, File.ContentLength)
  End Using
End Function

NTN

0
source

Source: https://habr.com/ru/post/1706622/


All Articles