简体   繁体   中英

Save and upload files in database ASP.NET Core 3.1 application

I am new to web development and I`ve got problems with uploading and saving files (for example.doc/.pdf/.jpeg) in database and I could not find a good solution on the Internet. My target is next: upload/retrieve file which is bound with table(EF Core, code-first approach). Is there any library for this or how can I organize architecture for my goal?

 public class MyModel
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [StringLength(255)]
        public string SomeProperty{ get; set; }
        //other properties

        //....

        //my property for file...
    }

I would add a property of type byte[] to the MyModel type.

    public byte[] fileData { get; set; }

You can then open the desired file and copy the FileStream into an object of type MemoryStream so that we then can call its ToArray method to generate a byte array. We use the object initializer to assign it to the fileData property.

    FileStream fs = File.OpenRead("{filePath}"); 
    MemoryStream ms = new MemoryStream();
    await fs.CopyToAsync(ms);
    MyModel model = new MyModel {fileData = ms.ToArray()};
    //Adding the object to the ChangeTracker of our DbContext and with calling
    //SaveChanges persisting these changes
    MyModelContext context = new MyModelContext();
    context.Add(model);
    await context.SaveChangesAsync();
    

As @DavidSeesSharp Told you can store it in bytes that is one approach But i prefer to use second approach

And the second approach is you can copy the file in your project and store the path of that file into your database.So, you can directly access that file by passing the path. If you need code then please clarify you proper use case i can assist you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM