【问题标题】:How to download a file using FileResult?如何使用 FileResult 下载文件?
【发布时间】:2013-08-18 23:08:21
【问题描述】:

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

【问题讨论】:

    标签: c# asp.net-mvc download


    【解决方案1】:

    尝试将您的 string image 行更改为 Stream image

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

    【讨论】:

    • 如何使用 Stream 对象?我似乎无法让它工作。
    • Stream image = = new FileStream(fileName, FileMode.Open)
    • 我得到了同样的错误。所以这意味着他没有找到文件?
    • @NanouPonette 在Stream image = ... 上设置断点并在调试模式下运行。
    【解决方案2】:

    你的方法是正确的。

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

    如果您使用~\\Qrcodes\\filename,它将转换为&lt;appRootDirectory&gt;\\QrCodes\\filename

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

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

    如果你不想这样做,你需要提供二维码文件夹的绝对路径。

    【讨论】:

    • 我也照你说的做了,但不幸的是没有成功。更新了我的问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 2011-01-30
    相关资源
    最近更新 更多