c# - How to store images on disk and link to database with EF? -
i have table
id | imagepath ------------------- 1 | ~/files/1.png
my model class has
public int64 id { ... } public string imagepath { ... }
i trying find approach store image on file. thinking in creating byte[]
property , write file when call savechanges
.
is possible? there event fires when changes saved can use in case?
or there better approach store path
on database , files
on disk?
in 1 of projects store files in folder , filepath in database linked entity(relation 1-to-1). created entity file byte[] property , domain service saving files on server. in insertfile call filehandler saves bytes on disk.
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); }
link in database filename (because there 1 folder, no reason storing full path)
filehandler code:
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); } } }
Comments
Post a Comment