Am new for hamdling Entity Framework.I use the following code for insert the file from fileupload button in mvc4
public ActionResult Index(NewUserModel newUser)
{
Resume newuserResume = new Resume();
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileextn = Path.GetExtension(fileName);
if (fileextn == ".pdf" || fileextn == ".doc")
{
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
newuserResume.Resumes = fileBytes;
Hrentitymodel.Resumes.Add(newuserResume);
Hrentitymodel.SaveChanges();
}
else {
ViewBag.FileExtn = "File Should be in .doc or .pdf Format";
}
}
}
return View("Index");
}
It will working fine which means the file stored in DB with Varbinary(max) Format. Now,How to view and download the file from sql db using entity framework in MVC4
Assuming a basic Model of:
public class Resume
{
public int ResumeID {get;set;}
public string Name { get; set; }
public byte[] Resume { get;set; }
}
Store the file using:
resume.Resume = new byte[file.ContentLength];
file.InputStream.Read(resume.Resume, 0, (file.ContentLength));
(which you are!)
To view the file you will want to return a FileContentResult.
In your view you can do something like:
@Html.ActionLink("View Resume", "ViewResume", "ResumeController", new { id = resume.ResumeID }, new { @target= "_blank" })
And the controller action will call the Action to return the file:
public FileContentResult ViewResume(int id)
{
if (id == 0) { return null; }
Resume resume = new Resume();
ResumeContext rc = new ResumeContext();
resume = rc.Resume.Where(a => a.ResumeID == id).SingleOrDefault();
Response.AppendHeader("content-disposition", "inline; filename=file.pdf"); //this will open in a new tab.. remove if you want to open in the same tab.
return File(resume.Resume, "application/pdf");
}
This is the basic method I have implemented when storing files in the DB.
To view the file
view
@{
if (Model.Logo != null)
{
string imageBase64 = Convert.ToBase64String(Model.Logo);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="@imageSrc" width="100" height="100" />
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.