How to store images on disk and reference the database using EF?

I have a table

ID | ImagePath
-------------------
 1 | ~/files/1.png

My model class has

public Int64 ID { ... }
public string ImagePath { ... }

I am trying to find an approach for storing an image in a file. I was thinking of creating a property byte[]and writing only the file when I SaveChangescalled.

Is it possible? Is there some kind of event that fires when saving changes that I can use only in this case?

Or is there some kind of better approach for storing in a database and on disk ? pathfiles

+3
source share
1 answer

FilePath ( 1 1). File with byte [] . InsertFile filehandler, .

public IQueryable<WebFile> GetFiles()
        {

            string path = "~/Upload";

            List<WebFile> webFiles = new List<WebFile>();

            if (string.IsNullOrEmpty(path)) return webFiles.AsQueryable();

            DirectoryInfo di = new DirectoryInfo(HttpContext.Current.Server.MapPath(path));

            foreach (FileInfo file in di.GetFiles())
            {

                webFiles.Add(new WebFile { FileName = file.Name });

            }

            return webFiles.AsQueryable();

        }

        public void InsertFile(WebFile file)
        {

            FileHandler.HandleFile(file);

        }

- ( , )

FileHandler:

public class FileHandler
    {
        public static void HandleFile(WebFile file)
        {

            string uploadDir = "~/Upload";

            if (!string.IsNullOrEmpty(uploadDir))
            {

                if (uploadDir.IndexOf("~/") == 0)

                    uploadDir = HttpContext.Current.Server.MapPath(uploadDir);

                if (uploadDir.LastIndexOf("/") == uploadDir.Length - 1)

                    uploadDir = uploadDir.Substring(0, uploadDir.Length - 1);

                string fullFileName = string.Format("{0}/{1}", uploadDir, file.FileName);

                if (File.Exists(fullFileName))
                {

                    string ext = fullFileName.Substring(fullFileName.LastIndexOf("."));

                    string fName = fullFileName.Substring(0, fullFileName.LastIndexOf("."));

                    fullFileName = string.Format("{0}_1{1}", fName, ext);

                }

                File.WriteAllBytes(fullFileName, file.FileContent);

            }

        }
    }
+1

Source: https://habr.com/ru/post/1793025/


All Articles