简体   繁体   English

在数据库 ASP.NET Core 3.1 应用程序中保存和上传文件

[英]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.我是 web 开发的新手,在数据库中上传和保存文件(例如 .doc/.pdf/.jpeg)时遇到问题,我在 Internet 上找不到好的解决方案。 My target is next: upload/retrieve file which is bound with table(EF Core, code-first approach).我的目标是下一个:上传/检索与表绑定的文件(EF Core,代码优先方法)。 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.我会将 byte[] 类型的属性添加到 MyModel 类型。

    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.然后您可以打开所需的文件并将 FileStream 复制到 MemoryStream 类型的 object 中,这样我们就可以调用它的 ToArray 方法来生成一个字节数组。 We use the object initializer to assign it to the fileData property.我们使用 object 初始化程序将其分配给 fileData 属性。

    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正如@DavidSeesSharp 所说,您可以将其存储在字节中,这是一种方法但我更喜欢使用第二种方法

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.如果您需要代码,请澄清您正确的用例,我可以为您提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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