我的视图中有一个带有 ActionLink 按钮“下载”的列表,我希望他们在单击链接时下载文件。该文件位于我项目的地图中。
看法:
<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>
控制器:
[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);
}
linkid 来自列表中选定的链接。然后我在我的数据库中查找与 linkid 匹配的 qrcode。从这个 qrcode 对象我得到图像名称。示例(qrcode-1337)。然后我不知道该怎么办。我查找存储我的项目的路径并将地图 Qrcodes 附加到它(存储所有图像的位置)和图像名称。这会返回一个他找不到的链接。
地图位置:
C:\Users\stage\Desktop\Immo-QR\Immo-QR\Immo-QR\Qrcodes
这似乎不起作用。我不确定应该如何使用 FileResult。谁能解释一下?或者告诉我另一种方式?
编辑:
一位用户建议我将图像放入我在地图 Qrcodes 下所做的 App_Data 文件中。
要保存文件,我使用以下代码:
字符串路径 = Server.MapPath("~");
System.IO.File.WriteAllBytes(path + "\\App_Data\\Qrcodes\\qrcode-" + qrcodeid + ".jpg", bytes);
如果我使用“~\App_Data\Qrcodes\qrcode-”而不是上面的,它也不起作用。
我仍然收到此错误:“/”应用程序中的服务器错误。无法找到该资源。
解决方案:
使用此代码它可以工作!
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");
}