Reputation: 1402
I have a list in my view with an ActionLink button 'Download' and I want them to download a file when they click the link. The file is located in a map in my project.
View:
<div id="right-column-links">
<h2>Your active links</h2>
@if (lstLinks.Count == 0)
{
<p>You have no active links yet.</p>
}
else
{
<table>
@foreach (var item in lstLinks)
{
<tr>
<td>@Html.DisplayFor(model => item.Url)</td>
<td>@Html.ActionLink("Put inactive", "LinkInActive", new { linkid=item.LinkId }, new { onclick = "return confirm('Are you sure you want this link inactive?');" })</td>
<td>@Html.ActionLink("Download Qrcode", "DownloadQrcode", new { linkid=item.LinkId })</td>
</tr>
}
</table>
}
</div>
Controller:
[HttpPost]
public FileResult DownloadQrcode(int linkid)
{
Qrcode Qrcode = DbO.getQrcodebyLinkId(linkid);
string image = Server.MapPath("~") + "\\Qrcodes\\" + Qrcode.Image;
string contentType = "image/jpg";
return File(image, contentType, "Qrcode-" + Qrcode.QrcodeId);
}
The linkid comes from the selected link in the list. Then I lookup what qrcode matches the linkid in my database. From this qrcode object I get the image name. Example (qrcode-1337). Then I'am not sure what to do. I lookup the path where my project is stored and attach the map Qrcodes to it (where all the images are stored) and the image name. This returns me a link that he doesn't find.
Map location:
C:\Users\stage\Desktop\Immo-QR\Immo-QR\Immo-QR\Qrcodes
This doesn't seem to work. I am not sure how I should use FileResult. Can anyone explain this? Or show me another way?
EDIT:
A user suggested me to put the images in the App_Data file which I did under a map Qrcodes.
To save the file I use this code:
string path = Server.MapPath("~");
System.IO.File.WriteAllBytes(path + "\\App_Data\\Qrcodes\\qrcode-" + qrcodeid + ".jpg", bytes);
If I use "~\App_Data\Qrcodes\qrcode-" instead of the above, It doesn't work either.
I still get this error: Server Error in '/' Application. The resource cannot be found.
SOLUTION:
With this code it works!
public FileStreamResult DownloadQrcode(int linkid)
{
Qrcode Qrcode = DbO.getQrcodebyLinkId(linkid);
string path = Server.MapPath("~");
Stream image = new FileStream(path + "\\App_Data\\Qrcodes\\" + Qrcode.Image + ".jpg", FileMode.Open);
return File(image, "image/jpeg");
}
Upvotes: 2
Views: 13159
Reputation: 754
Try changing your string image
line to Stream image
.
This will help understand if you can't read the file. Your return File
line will take a Stream with no issues.
Upvotes: 2
Reputation: 1585
Your approach is correct.
I think the path to the file is incorrect.
If you use ~\\Qrcodes\\filename
it will translate to <appRootDirectory>\\QrCodes\\filename
.
Also remember that IIS runs as a separate user in most cases, which does not have a home directory like a regular user.
I would suggest you move the Qrcodes to AppData folder or AppGlobalResources folder.
If you dont want to do that, you need to provide absolute path to Qrcodes folder.
Upvotes: 0