I am a beginner in ASP.Net MVC 5 and I want to know how to upload file in database and the display them to the user. I saw numerous example on internet related to above question. But all talks about putting file in some solution folder. But I want to upload file to database and be able to retrieve it in "Details View".
Issue: I am able to upload file in Database, but I am not sure how to Display the file link to user. Clicking on which user should be able to view/download the uploaded file. Below is my attempt.
Model:
public class File
{
public int Id { get; set; }
[StringLength(255)]
public string FileName { get; set; }
public byte[] Content { get; set; }
}
Controller:
// GET: FileUpload
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(File file, HttpPostedFileBase upload)
{
try
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
var tempfile = new File
{
FileName = System.IO.Path.GetFileName(upload.FileName),
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
tempfile.Content = reader.ReadBytes(upload.ContentLength);
}
file.Content = tempfile.Content;
}
_context.Files.Add(file);
_context.SaveChanges();
return RedirectToAction("Index");
}
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(file);
}
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
File f1 = _context.Files.Where(f => f.Id == id).SingleOrDefault();
if (f1 == null)
{
return HttpNotFound();
}
// NOT SURE WHAT TO HERE
return View(f1);
}
View: Details.chtml file
@model fileupload.Models.File
<h4>File</h4>
@* NOT SURE HOW TO HANDLE THE FILE LINK HERE*@
So, In the database I can see some binary content entry in "Content" Column. But I am not sure how can I display some link in the detail section. I want to display the file link in the details view. Clicking on which the file will get downloaded or something like preview. Kindly guide me.
EDIT 1
public FileContentResult Download(int id)
{
var file = _context.Files.First(f => f.Id == id);
var fileRes = new FileContentResult(file.Content.ToArray(), "application/pdf");
fileRes.FileDownloadName = file.FileName;
return fileRes;
}