Ronnie Overby
Ronnie Overby

Reputation: 46470

ASP.NET Store uploaded file sql server table

How do you store a file that was uploaded by an ASP.net webform into a sql server 2005 varbinary(max) field?

Here is what I have so far:

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 plain old ado.net example would be good. So would a linq to sql example.

Thanks

Upvotes: 3

Views: 5779

Answers (4)

InteXX
InteXX

Reputation: 6367

Here's a quick refactor of Ronnie's answer:

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

HTH

Upvotes: 0

Ronnie Overby
Ronnie Overby

Reputation: 46470

Here's how I did this 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);
}

Upvotes: 2

Jose Basilio
Jose Basilio

Reputation: 51468

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

Upvotes: 3

Spencer Ruport
Spencer Ruport

Reputation: 35107

This is generally considered bad form. It bloats your database and doesn't really offer any advantages over keeping all files in a hard drive folder and just storing the location of the file in the DB. Are you sure you want to do this?

Upvotes: 2

Related Questions