2

我的视图中有一个带有 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");
}
4

2 回答 2

2

尝试将您的string image线路更改为Stream image.

这将有助于了解您是否无法读取该文件。您的return File线路将毫无问题地采用 Stream。

于 2013-08-16T14:20:15.500 回答
0

你的方法是正确的。

我认为文件的路径不正确。

如果您使用~\\Qrcodes\\filename它将转换为<appRootDirectory>\\QrCodes\\filename.

还要记住,在大多数情况下,IIS 作为单独的用户运行,它没有像普通用户那样的主目录。

我建议您将二维码移至 AppData 文件夹或 AppGlobalResources 文件夹。

如果您不想这样做,则需要提供 Qrcodes 文件夹的绝对路径。

于 2013-08-16T14:06:21.800 回答