无法从服务器返回文件

时间:2015-06-24 13:29:46

标签: html asp.net asp.net-mvc

我正在尝试创建一个链接,以便用户可以下载已在服务器上的文件。

在我的控制器中我有:

public ActionResult downloadFile(int id)
        {
            DataAccess da = new DataAccess();
            PersonFile displayFile = new PersonFile();
            displayFile = da.getPersonFileByID(id);

            string mimeType = "application/pdf";

            return File(displayFile.FileData, mimeType, displayFile.FileName);
        }

然后在我看来,我有:

 <th class="editAddLabel">
        @Html.LabelFor(model => Model.PersonFile.FileName, "FileName")

        *@Html.ActionLink("Download file", "downloadFile", "PersonController", Model.id, null )*

    </th>

这是我第一次做这样的事情,但我觉得当人们点击链接时,它应该将模型的id发送到downloadFile方法,然后返回文件的内容。但是当我点击链接时,我什么都没得到。当我在downloadFile方法上设置断点时,没有任何反应让我相信甚至没有调用该方法。我能做错什么?

编辑:我还尝试了以下内容:

<input type="button" title="File" value="File" onclick="location.href='@Url.Action("downloadFile", "PersonController",  new { id = Model.id })'; }" />
    </th>

我的错误:

Server Error in '/' Application.

    The resource cannot be found.

    Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 

    Requested URL: /PersonController/downloadFile

3 个答案:

答案 0 :(得分:1)

您的ActionLink格式不正确,并且未随请求发送ID。试试这个:

@Html.ActionLink("Download file", "downloadFile", "PersonController", new { id = Model.id }, null )

答案 1 :(得分:0)

只是一个猜测,但您可以将返回类型设置为&#34; FileResult&#34;像:

public FileResult downloadFile(int id)
    {
        DataAccess da = new DataAccess();
        PersonFile displayFile = new PersonFile();
        displayFile = da.getPersonFileByID(id);

        string mimeType = "application/pdf";

        return File(displayFile.FileData, mimeType, displayFile.FileName);
    }

进一步详情: Download file of any type in Asp.Net MVC using FileResult?

答案 2 :(得分:0)

查看您的错误,您要求的网址似乎是/PersonController/downloadFile。这对我来说似乎是错误的,您没有传递与某个人相关的ID,而且MVC路由应该是/person/downloadfile而不是personcontroller

尝试Url.Action("downloadFile", "Person", new { @id = Model.Id }