Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file from link inside my webpage

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 ?

like image 585
user2978444 Avatar asked Nov 14 '13 10:11

user2978444


People also ask

How do I download a file from my link?

Most files: Click on the download link. Or, right-click on the file and choose Save as. Images: Right-click on the image and choose Save Image As. Videos: Point to the video.

How do I click and download a link in HTML?

The download attribute specifies that the target (the file specified in the href attribute) will be downloaded when a user clicks on the hyperlink. The optional value of the download attribute will be the new name of the file after it is downloaded.


1 Answers

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;
}
like image 83
mehmet mecek Avatar answered Oct 09 '22 21:10

mehmet mecek