簡體   English   中英

如何在磁盤上存儲圖像並使用EF鏈接到數據庫?

[英]How to store images on disk and link to database with EF?

我有一張桌子

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

我的模特課有

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

我試圖找到一種方法將圖像存儲在文件上。 我正在考慮創建一個byte[]屬性,只在我調用SaveChanges時才寫入該文件。

可能嗎? 保存更改時是否會觸發某些事件,我只能在這種情況下使用?

或者是否有更好的方法來存儲數據庫中的path和磁盤上的files

在我的一個項目中,我將文件存儲在文件夾中,而FilePath存儲在數據庫中,用於鏈接實體(關系是1對1)。 我剛剛創建了帶有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);

            }

        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM