如何使用FileResult下载文件?

时间:2013-08-16 13:57:39

标签: c# asp.net-mvc download

我的视图中有一个列表,其中包含一个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来自列表中的选定链接。然后我查找qrcode与我的数据库中的linkid匹配的内容。从这个qrcode对象我得到图像名称。示例(qrcode-1337)。那我不知道该怎么办。我查找存储项目的路径,并将地图Qrcodes附加到它(存储所有图像的位置)和图像名称。这会给我一个他找不到的链接。

地图位置

C:\用户\阶段\桌面\ IMMO-QR \ IMMO-QR \ IMMO-QR \ Qrcodes

这似乎不起作用。我不确定如何使用FileResult。有谁能解释一下?或者告诉我另一种方式?

修改

用户建议我将图像放在我在地图Qrcodes下做的App_Data文件中。

要保存文件,请使用以下代码:

string path = Server.MapPath(“〜”);

        System.IO.File.WriteAllBytes(path + "\\App_Data\\Qrcodes\\qrcode-" + qrcodeid + ".jpg", bytes);

如果我使用“〜\ App_Data \ Qrcodes \ qrcode-”代替上述内容,它也不起作用。

我仍然收到此错误:'/'应用程序中的服务器错误。无法找到该资源。

SOLUTION:

使用此代码可以正常工作!

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");
}

2 个答案:

答案 0 :(得分:2)

尝试将string image行更改为Stream image

这将有助于了解您是否无法读取该文件。您的return File行会在没有问题的情况下使用Stream。

答案 1 :(得分:0)

你的方法是正确的。

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

如果您使用~\\Qrcodes\\filename,则会转换为<appRootDirectory>\\QrCodes\\filename

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

我建议您将Qrcodes移动到AppData文件夹或AppGlobalResources文件夹。

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

相关问题