How to get downloadable files to view from controller

242 Views Asked by At

I am using entity framework in asp.net mvc-5 and I have provided functionality to upload files that are stored in SQL Server as FILESTREAM (files aren't stored in folders but their content as byte array in database table). Now I want to get those files from database and make them appear on a view(there would be a link as file name on which you can click and it would start download process). Also, there are columns in table that separately hold file name, file extension and its content. I will provide you my model and controller for upload so you have idea how I did it:

public class File
{
    [Key]
    public int fileId{ get; set; }

    [Required]
    public byte[] fileContent{ get; set; }

    public string fileUrl { get; set; }

    public string fileExtension{ get; set; }

    public string fileName{ get; set; }
}

[HttpPost]
public ActionResult UploadFile([Bind(Include = "Title, File")] FileViewModel 
fileModel)
{
    if (ModelState.IsValid)
    {
        var fileData = new MemoryStream();
        fileModel.File.InputStream.CopyTo(fileData);

        string name = Path.GetFileName(fileModel.File.FileName);
        string extension= Path.GetExtension(fileModel.File.FileName);

        var file = new FileModel { fileName = name, 
        fileExtension= extension, fileContent= fileData.ToArray() };
        _context.File.Add(file);

        _context.SaveChanges();

        return RedirectToAction("UploadFile");
    }
    return View(fileModel);
}

I have tried to search for answers, but every response does something that I don't need. I have looked up on FileStreamResult but I can't fit it into my needs from this point of view.

1

There are 1 best solutions below

1
On

try this for download file.

var fileanme ="your filename with path";
var fileBytes = System.IO.File.ReadAllBytes(fileanme);
Response.AppendHeader("Content-Disposition", "inline; filename='abc.pdf'");
return File(fileBytes, "application/pdf");