开发者

jQuery delivery of a file with AJAX call

开发者 https://www.devze.com 2023-03-10 02:51 出处:网络
If I have an AJAX call that returns, say, a CSV, how do I get the browser to prompt the user for a download?Below, the ProductsExport will return th开发者_如何转开发e CSV in the success data.I just ne

If I have an AJAX call that returns, say, a CSV, how do I get the browser to prompt the user for a download? Below, the ProductsExport will return th开发者_如何转开发e CSV in the success data. I just need what I'd replace the // Deliver file to user line with...

$.ajax({
    type: "POST",
    url: "/Search/ProductsExport",
    data: $('#CustomerId').serialize(),
    success: function (data) {

        // Deliver file to user!!

    },
    error: function (xhr, textstatus, errorThrown) {
        alert('Error');
    }
})

My C# code on the back end looks like so:

var aFileContent = Encoding.ASCII.GetBytes(export);
var aMemoryStream = new MemoryStream(aFileContent);
return File(aMemoryStream, "text/plain",
    string.Format("{0}.csv", CustomerId));


You cannot as far as I'm aware. You can't use ajax here as a file download. YEs - its a support datatype as per jQuery but not for a file. You need to link to the file for a non ajax request either via a link or a jQuery get request.

See: Unable to open download save dialog and "datatype" on http://api.jquery.com/jQuery.ajax/


Alternative solution to your problem is have an AJAX function return an actual URL that will download csv (similar to your C# backendcode). The client side will then launch the URL using window.open(url)


Why does it have to be ajax? Just build your url and do a window.location.href to execute your call. All you seem to be passing it is a customerId, so that should be pretty easy.

Ajax operations are meant to allow a user to stay on the page while operations continue behind the scenes. A file download will keep the user on the page and just download the file, so there's no benefit to using ajax in this siutation. Something like this perhaps:

window.location.href = "/Search/ProductsExport?" + $.param($('CustomerId'))
0

精彩评论

暂无评论...
验证码 换一张
取 消