Download file from link inside my webpage

user2978444 picture user2978444 · Nov 14, 2013 · Viewed 29.8k times · Source

I have Webpage with table of objects.

One of my object properties is the file path, this file is locate in the same network. What i want to do is wrap this file path under link (for example Download) and after the user will click on this link the file will download into the user machine.

so inside my table:

@foreach (var item in Model)
        {    
        <tr>
            <th width ="150"><p><b><a href="default.asp" target="_blank">Download</a></b></p></th>
            <td width="1000">@item.fileName</td>
            <td width="50">@item.fileSize</td>
            <td bgcolor="#cccccc">@item.date<td>
        </tr>
    }
    </table>

I created this download link:

<th width ="150"><p><b><a href="default.asp" target="_blank">Download</a></b></p></th>

I want this download link to wrap my file path and click on thie link will lean to my controller:

public FileResult Download(string file)
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(file);
}

What i need to add to my code in order to acheive that ?

Answer

mehmet mecek picture mehmet mecek · Nov 14, 2013

Return FileContentResult from your action.

public FileResult Download(string file)
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(file);
    var response = new FileContentResult(fileBytes, "application/octet-stream");
    response.FileDownloadName = "loremIpsum.pdf";
    return response;
}

And the download link,

<a href="controllerName/[email protected]" target="_blank">Download</a>

This link will make a get request to your Download action with parameter fileName.

EDIT: for not found files you can,

public ActionResult Download(string file)
{
    if (!System.IO.File.Exists(file))
    {
        return HttpNotFound();
    }

    var fileBytes = System.IO.File.ReadAllBytes(file);
    var response = new FileContentResult(fileBytes, "application/octet-stream")
    {
        FileDownloadName = "loremIpsum.pdf"
    };
    return response;
}