如何在 ASP.NET MVC 4 和 jquery 中使用 web api 下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12975886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:11:18  来源:igfitidea点击:

How to download a file using web api in ASP.NET MVC 4 and jquery

jqueryasp.net-mvc-4asp.net-web-api

提问by Yasser Shaikh

I am new to using ASP.NET MVC 4 with Web Api.

我是 ASP.NET MVC 4 和 Web Api 的新手。

I want to allow user to download a file, this file I will be creating on the server side. For creating the file I have managed to get hold of the following code

我想允许用户下载一个文件,我将在服务器端创建这个文件。为了创建文件,我设法掌握了以下代码

[ActionName("Export")]
public HttpResponseMessage PostExportData(SomeModel model)
{           
    string csv = _service.GetData(model);
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StringContent(csv);
    //a text file is actually an octet-stream (pdf, etc)
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    //we used attachment to force download
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = "file.csv";
    return result;            
}

HOW TO CALL THIS WEB API METHOD USING JQUERY ?

如何使用 JQUERY 调用此 Web API 方法?

But I am not sure of how to call this web api using jquery and make it return me a file, with a "save as / open" option that you normally get when downloading any file.

但我不确定如何使用 jquery 调用此 Web api 并使其返回一个文件,并带有“另存为/打开”选项,您通常会在下载任何文件时获得该选项。

Can some one please help me and guide me in how to make the call and download the file. Thanks.

有人可以帮助我并指导我如何拨打电话和下载文件。谢谢。

采纳答案by Mihalis Bagos

You can do something like this inside the view where you want to use jquery. I assume the name of the controller is ExportController. You also have to break down the model variables, or alternatively collect the model inside HttpResponseMessage PostExportData(SomeModel model) via some other way.

您可以在要使用 jquery 的视图中执行类似操作。我假设控制器的名称是 ExportController。您还必须分解模型变量,或者HttpResponseMessage PostExportData(SomeModel model) 通过其他方式收集模型内部。

html:

html:

<a class="export">export</a>

javascript:

javascript:

<script>
$('a.export').click(function(e) {
    e.preventDefault();  //stop the browser from following
    window.location.href = '@Url.Action('Export', 'ExportController', new { property = model.property, property = model.property2 })';
});
</script>

To use POST

使用 POST

function UpdateForm(modelObject) {
   if ($('#hidden-form').length < 1)
   {
       $('<form>').attr({
           method: 'POST',
           id: 'hidden-form',
           action: '@Url.Action('Export', 'Export')'
       }).appendTo('body');
   }
   $('#hidden-form').html('');
   for(var propertyName in modelObject) {
       $('<input>').attr({
            type: 'hidden',
            id: propertyName,
            name: propertyName,
            value: modelObject[propertyName]
       }).appendTo('#hidden-form');
    }
}

$('a.export').click(function(e) {
    e.preventDefault();
    var modelObject = { property1 : "property1" };
    UpdateForm(modelObject);
    $('#hidden-form').submit();
});

Then you can just post #hidden-formvia js which will trigger the file download

然后你可以#hidden-form通过 js发布,这将触发文件下载

Update:This is a full example for posting, and its not checked for typos etc so debug any minor errors.

更新:这是一个完整的发布示例,没有检查拼写错误等,因此调试任何小错误。