Freddy
Freddy

Reputation: 1765

Save files in database with entity framework

I have an ASP.NET MVC solution built on Entity Framework with Microsoft SQL Server 2008. I need to create a function that lets my users upload files.

What I would like is:

Upvotes: 18

Views: 39117

Answers (5)

Enderg
Enderg

Reputation: 11

I was thought that best way of storing files with database it is storing only string path of this files in server (in other words, storing files in folders while, in database storing only their string path). Something like this I use (there also random naming system in order to avoid same naming problem among many users while keeping all data in same folder):

public static class FileExtensions
{
    public static string RootPath { get; set; }

    public static bool IsValidSize(this IFormFile file, float kb = 20)
        => file.Length <= kb * 1024;

    public static bool IsCorrectType(this IFormFile file, string contentType = "image")
        => file.ContentType.Contains(contentType);

    public static async Task<string> SaveAsync(this IFormFile file, string path = "data")
    {
        string extension = Path.GetExtension(file.FileName);
        string fileName = Path.GetFileNameWithoutExtension(file.FileName).Length > 32 ?
            file.FileName.Substring(0, 32) :
            Path.GetFileNameWithoutExtension(file.FileName);
        fileName = Path.Combine(path, Path.GetRandomFileName() + fileName + extension);
        using (FileStream fs = File.Create(Path.Combine(RootPath, fileName)))
        {
            await file.CopyToAsync(fs);
        }
        return fileName;
    }
}

Upvotes: 0

Craig Stuntz
Craig Stuntz

Reputation: 126547

The "right" way to store a file in a SQL Server 2008 database is to use the FILESTREAM data type. I'm not aware that the Entity Framework supports that, but you can certainly try and see what happens.

That said, most of the time when people do this, they don't store the file in the database. Doing so means that you need to go through ASP.NET and the database server just to serve a file which you could be serving directly from the web server. It can also somewhat complicate the backup picture for your database and site. So when we upload files to our MVC/Entity Framework, we store only a reference to the file location in the database, and store the file itself elsewhere.

Obviously, which strategy is right for you depends a lot on the particulars of your application.

Upvotes: 9

Abdul Rehman Sayed
Abdul Rehman Sayed

Reputation: 6672

A working example (only for file upload because this one comes first in google) on basis of @Thomas's answer :

public void AddDocument(HttpPostedFileBase file)
        {
            try
            {                
                    using (TransactionScope scope = new TransactionScope())
                    {
                        try
                        {
                            using (var ctx = new Entities())
                            {

                            EntityDoc doc = new EntityDoc(); //The document table 

                            doc.DocumentFileName = file.FileName; //The file Name

                            using (var reader = new System.IO.BinaryReader(file.InputStream))
                            {
                                doc.DocumentFile = reader.ReadBytes(file.ContentLength); // the Byte [] Field
                            }
                            ctx.EntityDocs.Add(doc);


                                ctx.SaveChanges();
                                scope.Complete();
                            }
                        }
                        catch (Exception ex)
                        {                          
                            throw ex;
                        }
                    }

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

Upvotes: 0

George Stocker
George Stocker

Reputation: 57872

Here's how I do it for Podcasts:


ID     Title         Path                    Summary              UploadDate
---    -----        --------              ----------------        -----------
1     TestPodcast   /Podcasts/ep1.mp3      A test podcast         2010-02-12

The path stores a reference to the physical location of the Podcast. I used a post from Scott Hanselman on File Uploads with ASP.NET MVC to deal with the file upload part.

Upvotes: 5

Thomas Levesque
Thomas Levesque

Reputation: 292405

In your entity model, map the BLOB database column to a byte[] property. Assign the content of the uploaded file to that property of the entity object, and save changes in the ObjectContext.

To compute a hash, you can use the MD5CryptoServiceProvider class

Upvotes: 46

Related Questions