Download a file using a POST request rather than GET
I have an ASP.NET MVC app. On one page I've got a button to allow a user to download a CSV file based on some values on the page set by the user (slider ranges, check boxes, etc.) without leaving the page. The file is returned by my Controller class by a method that returns a FileResult.
Currently, my javascript onClick
method is implemented as follows, with a bit of jQuery:
function DownloadCSV() {
var url = <%=Action("DownloadCSV", "Controller")%> + '?' +
$.param({
SomeValue: $("#valuefromform").val(),
OtherValue: $("#anothervaluefromform").val(),
...
});
window.location = url;
}
That part works perfectly, so onto the question: I开发者_如何转开发s it possible to rewrite this method so it 'posts' the query rather than using a 'get' query string?
(I have tried using an AJAX request, which can POST fine, but although I get the file data back this is part of the XHR response and I can't work out how to make it download as a file so if there's a way of doing it that way that would be great too!)
You could setup a form:
<% using (Html.BeginForm("DownloadCSV", "Controller", null, FormMethod.Post, new { id = "myform" })) { %>
<input type="hidden" id="someValue" name="someValue" value="" />
<input type="hidden" id="otherValue" name="otherValue" value="" />
<% } %>
and when time comes to download simply submit this form:
function DownloadCSV() {
$('#someValue').val($('#valuefromform').val());
$('#otherValue').val($('#anothervaluefromform').val());
$('#myform').trigger('submit');
}
Another possibility is to build this form entirely dynamically and inject it into the DOM before submission.
This probably isn't the answer you're seeking, but you could set up a POST request via ajax like you've been doing, but rather than return the file, return the path and/or filename of the csv file you created. Your post action would be modified to have one additional step to save that csv file to the server with a unique name (which gets returned).
You could then do a the same window.location = url
logic and then pass in the filename returned to you via the XHR request.
In pseudo code:
$.post(/*bunch of ajax stuff*/,
success : function(result) { document.location = 'CSVDownloader/?filename=' + result ; }
);
Where CSVDownloader is someone that wraps the download and returns the proper header type. Best practice dictates you don't open up any web-accessable folders to have write permissions, so I'm assuming the file gets saved somewhere behind the root of the web server.
精彩评论