просмотреть и скачать файл из sql db с помощью Entity FrameWork

1

Является новым для hamdling Entity Framework. Я использую следующий код для вставки файла из кнопки загрузки файла в 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");
        }

Он будет работать отлично, что означает файл, хранящийся в БД с использованием формата Varbinary (max). Теперь, как просмотреть и загрузить файл из sql db с использованием структуры сущности в MVC4

Теги:
entity-framework
asp.net-mvc-4
entity-framework-4.1

2 ответа

3

Предполагая базовую модель:

public class Resume
{
public int ResumeID {get;set;}
public string Name { get; set; }
public byte[] Resume { get;set; }
}

Сохраните файл, используя:

resume.Resume = new byte[file.ContentLength];
file.InputStream.Read(resume.Resume, 0, (file.ContentLength));

(который вы есть!)

Чтобы просмотреть файл, вы захотите вернуть FileContentResult.

По вашему мнению, вы можете сделать что-то вроде:

@Html.ActionLink("View Resume", "ViewResume", "ResumeController", new { id = resume.ResumeID }, new { @target= "_blank" })

И действие контроллера вызовет действие для возврата файла:

    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");
    }

Это основной метод, который я реализовал при хранении файлов в БД.

0

Чтобы просмотреть файл

Посмотреть

 @{
     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" />
       }
  }
  • 0
    Кажется, ваш код адресован только в том случае, если файл является изображением, а не просто файлом в формате doc. Я считаю, что вопрос был более актуальным, если вы сохраните форму, в которой загружен файл / файлы, как бы вы затем просматривали эту форму и, следовательно, видели указанные файлы почему его код для .pdf или .doc

Ещё вопросы

Сообщество Overcoder
Наверх
Меню