views:

730

answers:

4

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

+1  A: 

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?

Spencer Ruport
there are pros and cons of both. compromise is sql server 2008's file stream.
Darren Kopp
What are some of the pros?
Spencer Ruport
I think if you are dealing with an internal application and have relatively small files or documents where you are concerned with versioning it can be very useful. I worked for an imaging company where it was very nice to store thumbnails and small files in the database with pointers to the larger files on central storage.
James Avery
@Spencer Ruport: Backups. Much easier to reliably backup the database and be sure that the files go with it and you're not left with a bunch of file links that no longer work. This is, I suppose, related to James Avery's comment about versioning above. The security is also more straightforward, as you needn't worry about granting the web user file system access of any kind.
Yadyn
@Yadyn: If the web user creates the file you don't have to worry anyway. And I don't feel that the hassle of a 16 gig database is worth the minor convenience of not setting up another backup task.
Spencer Ruport
+2  A: 

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

Jose Basilio
A: 

My this answer might help.

Canavar
A: 

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);
}
Ronnie Overby