2

I have uploaded a file into my database previously, now I want to download that file from my database.

Can anyone show me how? I am new to C# and ASP.NET MVC.

Controller :

public ActionResult Details(string id = null)
{
        Assignment assignment = db.Assignments.Find(id);

        if (assignment == null)
        {
            return HttpNotFound();
        }

        return View(assignment);
}

Model:

public string AssignmentID { get; set; }
public Nullable<System.DateTime> SubmissionDate { get; set; }
public string Status { get; set; }
[Range(0,100, ErrorMessage="Only Value between 0-100 is accepted.")]
public Nullable<decimal> Mark { get; set; }
public string Comments { get; set; }
public byte[] FileLocation { get; set; }

View:

<div class="display-label">
    <%: Html.DisplayNameFor(model => model.FileLocation) %>
</div>
<div class="display-field">
    <%: Html.DisplayFor(model => model.FileLocation) %>
</div>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
WeakTaenie
  • 247
  • 2
  • 6
  • 14

3 Answers3

6

Since you have the a Stream or byte[] or a path of a file, you can use the File() method that comes from Controller base class, and respond this file as an ActionResult, for sample:

public ActionResult Details(string id = null)
{
     Assignment assignment = db.Assignments.Find(id);

     if (assignment == null)
     {
         return HttpNotFound();
     }

     return File(assigment.FileLocation, "content/type", "fileName.extension");
}

Remember to get the right content-type and add a fileName with the correct extension.

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
1

Based on how you're retrieving the file from your database, you can use ASP.NET MVC's File() helper method to return your file to the client.

This blog article has a very good description of how to use the File() helper and what ends up getting returned.

Hope this helps.

David Hoerster
  • 28,421
  • 8
  • 67
  • 102
1

You have to use @url.action to display images on view :

View :

<%: Url.Action("ImageDetails","// your controller name//", new{ id = item.ID }) %>

and in your action:

public ActionResult ImageDetails(string id = null)
{
     Assignment assignment = db.Assignments.Find(id);

     return File(assignment.FileLocation, "content/type", "file.extension");
}

Remember to get the right content-type and add file correct extension otherwise file will not be rendered properly in view.

If you want only to download file not display then :-

public ActionResult Details(string id = null)
{
     Assignment assignment = db.Assignments.Find(id);

     return File(assignment.FileLocation, "content/type", "file.extension");
}
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69