How can I call an MVC FileContentResult by Jquery and get it to prompt the user to save on it's return?

喜夏-厌秋 提交于 2019-12-01 07:33:20

You can't do that. Forget about that. It is impossible to download files using AJAX. In fact the AJAX call will work, you will hit the server, the server will send the file contents back to the client, the AJAX success callback will be triggered and passed as argument the contents of the file and that's where everything ends for you. Using javascript you cannot, for absolutely obvious reasons, save directly the file to the client computer and you cannot prompt for the Save As dialog.

So instead of using AJAX simply create an anchor:

@Html.ActionLink("download spreadsheet", "GetSpreadsheet", new { id = "123" })

Now if the server set the Content-Disposition header to attachment the browser will prompt the user to download and save the file at some chosen location on his computer.

If you don't want to use an anchor, use a hidden iframe and set the src of the iframe to the url of the file to be downloaded.

<iframe id="hiddenFrame" src="" style="display:none; visibility:hidden;"></iframe>

Instead of the '$.post(...)' line use:

 downloadSpreadsheet('123');

 function downloadSpreadsheet(id) {
    var url = '@Url.Content("~/YourControllerName/GetSpreadsheet")' + "?id=" + id;
    $('#hiddenFrame').attr('src', url);
}

Or you can give a try on the jQuery Plugin for Requesting Ajax-like File Downloads

Using the plugin, you can download by invocking:

jQuery.download(url, data, method)

You can use this in JavaScript:

function downloadSpreadsheet(id) {
    window.location.href = '@Url.Action("GetSpreadsheet", "Home")?id=' + id;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!