[英]view and download File from sql db using Entity FrameWork
Am new for hamdling Entity Framework.I use the following code for insert the file from fileupload button in mvc4 我是Hamdling Entity Framework的新手。我使用以下代码从mvc4中的fileupload按钮插入文件
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. 它将正常工作,这意味着存储在具有Varbinary(max)格式的DB中的文件。 Now,How to view and download the file from sql db using entity framework in MVC4
现在,如何使用 MVC4中的实体框架从sql db查看和下载文件
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. 要查看该文件,您需要返回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: 并且控制器操作将调用Action以返回文件:
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. 这是我在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" />
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.