2015-12-30 57 views
0

我有一个Asp.Net MVC项目,并在它的一页上,用户可以编辑加载的数据到表(更改图像,字符串,项目顺序等... )。从HttpPost保存返回文件Asp.Net MVC方法

完成所有编辑后,客户端将按下“下载”按钮,并将生成的xml文件保存在他的硬盘上,以便将来进行下一次操作。

所以我有一个简单的HTML表单:

$scope.sendForm = function() { 

    // some preparations to send image data through json 
    for (var i = 0; i < $scope.data.Items.length; i++) { 
     $scope.data.Items[i].ImageAsString = $scope.data.Items[i].Image; 
    } 

    $http.post("Download", { array: $scope.data }) 
     .success(function (responseData) { 
      console.log(responseData); 
     }) 
     .error(function (responseData) { 
      console.log("Error !" + responseData); 
     }); 
}; 

这个函数被调用后,准备HTTP:

<form name="mainForm" data-ng-submit="sendForm()" ng-controller="ImportController" novalidate enctype="multipart/form-data"> 

    <!-- table structure definition removed for briefing --> 

    <td> 
     {{data.Items[$index].Id}} 
    </td> 
    <td> 
     <img class="center-cropped" ng-src="data:image/jpg;base64, {{data.Items[$index].Image}}"> 
    </td> 
    <td> 
     <input class="form-control" type="text" value="{{data.Items[$index].LastName}}" /> 
    </td> 

    <td> 
     <input class="form-control" type="text" value="{{data.Items[$index].FirstName}}" /> 
    </td> 
    <td> 
     <input class="form-control" type="text" value="{{data.ClaimItems[$index].MiddleName}}" /> 
    </td> 
    <input class="btn-success" id="submit-btn" type="submit" data-ng-disabled="mainForm.$invalid" value="Download" /> 

</form> 

这种形式的数据通过angularJs函数调用看起来像发发送请求发送到asp.net mvc 下载行动:

[HttpPost] 
    public FileResult Download(ItemsArrayWrapper array) 
    { 
     // here goes incoming data processing logic 
     // ... 

     return File(array.ConvertToItemsArray().Serialize(), "text/xml", name); 
    } 

我想让我的下载方法返回FileResult,因此,客户端上将出现文件保存对话框。但没有任何事情发生。我试过构造各种Response头文件,返回不同的MimeTypes,改变返回类型的Download方法,甚至尝试从Download方法调用[HttpGet]方法,但客户端上仍然没有任何东西出现。

在浏览器网络监控中搜索 - 仅发送一个POST请求。

是否有可能从HttpPost方法发送数据到客户端,这是从这样的方式从angularJs函数调用?我错过了什么,为什么保存对话框不显示在浏览器中?

或者任何人都可以提出任何其他更合适的解决方案来实现这一目标吗?

+0

什么是Post Request的HttpResponse状态码 - 200或500?仅用于测试,您可以尝试使用带有一些虚拟数据的ActionLink(带有HttpGet)来查看文件下载是否有效? – user1672994

+1

您将需要处理ajax响应,如[此问题](http://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post)。类似的方法使用打字机和一个名为FiledSaver库可以找到[在这个其他问题](http://stackoverflow.com/questions/14215049/how-to-download-file-using-angularjs-and-calling-mvc- api) –

+0

@ user1672994:HttpResponse是200,并且我无法通过Get发送此表单数据,因为我必须发送图像数据。我通过asp有以前的工作实现。net mvc + jQuery,现在被拖拽,试图通过angularJs来实现。 – Fragment

回答

1

我希望我的下载方法返回FileResult,所以,一个保存对话框 文件将出现在客户端上。但没有任何事情发生。

这是正常的,什么都没有发生。我建议你不要使用AJAX下载文件。只需构建一个普通的隐藏HTML表单,然后自动提交此表单到Download控制器操作。然后会出现文件保存对话框,提示用户保存文件。

如果你绝对需要做到这一点使用AJAX则应该注意的是,你可以使用HTML5 FileAPI,让您保存在AJAX回调的二元响应。但是请注意,只有在现代浏览器中才有效,如果您需要在网站中支持一些较旧的浏览器,则无论如何您都需要第一种方法。