简体   繁体   English

FileResult在mvc3中不提示

[英]FileResult is not prompt in mvc3

I create MVC 3 application in vs 2010. I try to a download a file in the filder. 我在vs 2010中创建了MVC 3应用程序。我尝试在filder中下载文件。

this is my Action in MVC. 这是我在MVC中的操作。 Please see my code. 请看我的代码。

    //[HttpPost]
    public FileResult Download(string url, string cnt)
    {
        if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(cnt))
        {
            return File(url, cnt);
        }
        else
        {
            return null;
        }

    }



 <input type="button" id="@(Model.ControlID)_bio_view" class="changepasswordbutton" value="View" />

And i create a jQuery function in my .cshtml file 我在我的.cshtml文件中创建一个jQuery函数

 function ViewFile(url, cnt) {
    $.post('@(Url.Action("Download"))?url=' + url + '&cnt=' + cnt)
}
 $('#@(Model.ControlID)_bio_view').click(function (e) {

    ViewFile($('#bio_file_url').val(), $('#bio_file_url').attr("cnttype"));

});

This function is fired correctly when i click the Download button. 当我单击下载按钮时,此功能已正确触发。 But no file download window is prompted. 但是没有提示文件下载窗口。

Please help. 请帮忙。

No, you cannot download files using an AJAX request. 不可以,您不能使用AJAX请求下载文件。 You need to redirect the browser to the target url instead of sending an AJAX request: 您需要将浏览器重定向到目标网址,而不是发送AJAX请求:

function ViewFile(url, cnt) {
    window.location.href = '@(Url.Action("Download"))?' + 
        'url=' +  encodeURIComponent(url) + 
        '&cnt=' + encodeURIComponent(cnt);
}

Also bear in mind that the File function expects as first argument an absolute physical path to the file such as: 还请记住, File函数期望将File的绝对物理路径作为第一个参数,例如:

public ActionResult Download(string url, string cnt)
{
    if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(cnt) && File.Exists(url))
    {
        return File(url, cnt);
    }
    return HttpNotFound();
}

Also if you want to prompt for the file to download you need to specify a filename (3rd argument of the File function): 另外,如果要提示下载文件,则需要指定文件名(File函数的第3个参数):

return File(@"c:\reports\foo.pdf", "application/pdf", "foo.pdf");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM