[英]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.