ASP.net WebAPI returns file via ajax call

I'm currently looking for a way to force download a file that is returned through a WebAPI controller.

I used http://www.shawnmclean.com/blog/2012/04/force-download-of-file-from-asp-net-webapi/ as a link.

On my client, I use the ajax GET call to send the object id and try to upload the file

exportList: (foo, callback) => path = '/api/export/id' path = path.replace("id", foo.id) $.ajax( url: path, dataType: 'text', success: (data) => callback(data) error: (data) => callback(false) ) 

On the server side, I have the above URI redirected to the method below

  [AcceptVerbs("GET")] public HttpResponseMessage ExportList(int id) { string file = fooService.ExportList(id); if (file == null) { return Request.CreateResponse(HttpStatusCode.NoContent); } HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StringContent(file); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = "List.csv"; return result; } 

The fooService.ExportList method simply creates a csv string.

When viewing a request, it is returned to the client, there is a csv line in the response, but the client is not requested or loaded.

Can this be done correctly?

+4
source share
2 answers

I think you are using javascript due to dynamic id? If you can post directly using the form, use this solution. If you really need javascript, use this piece of code to simulate the action of a form:

 $.download = function (url, data, method) { if (url && data) { //data can be string of parameters or array/object data = typeof data == 'string' ? data : jQuery.param(data).replace("\+", " "); data = data.replace(/\+/g, " "); var inputs = ''; jQuery.each(data.split('&'), function () { var pair = this.split('='); inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />'; }); //send request jQuery('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>') .appendTo('body').submit().remove(); }; }; 

Code to call download (instead of ajax call):

 path = '/api/export/id' path = path.replace("id", foo.id) $.download(path); 
+2
source

do not use ajax to request downloads. complete the full GET request. if you want, open the download in a new window.

 <a href="..." target="_blank">download file</a> 
+1
source

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


All Articles