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 ?
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With