Upload a file using a POST request, not a GET

I have an ASP.NET MVC application. On one page, I have a button that allows the user to download the CSV file based on some values ​​on the page specified by the user (sliders ranges, check boxes, etc.) without leaving the page. The file is returned by my Controller class with a method that returns a FileResult.

Currently, my javascript onClickmethod is implemented as follows: jQuery bit:

function DownloadCSV() {
    var url = <%=Action("DownloadCSV", "Controller")%> + '?' +
                  $.param({
                      SomeValue: $("#valuefromform").val(),
                      OtherValue: $("#anothervaluefromform").val(),
                      ...
                  });

    window.location = url;
}

This part works fine, so the question is: is it possible to rewrite this method so that it "sends" the request and does not use the "get" request line?

(I tried using an AJAX request that POST might work fine, but although I am returning the file data, this is part of the XHR response, and I cannot figure out how to make it loadable as a file, so if there is a way to do it in such a way that it was would be great!)

+3
source share
2 answers

You can customize the 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 the download time comes, just submit this form:

function DownloadCSV() {
    $('#someValue').val($('#valuefromform').val());
    $('#otherValue').val($('#anothervaluefromform').val());
    $('#myform').trigger('submit');
}

Another possibility is to build this form completely dynamically and inject it into the DOM before submitting it.

+9
source

, , , , POST- ajax, , , , / csv . - , csv ( ).

window.location = url, , XHR.

:

$.post(/*bunch of ajax stuff*/,
    success : function(result) { document.location = 'CSVDownloader/?filename=' + result ; }
);

CSVDownloader - , . , - , , , - -.

0

Source: https://habr.com/ru/post/1787269/


All Articles