Thursday 15 September 2011

javascript - Downloading a file in MVC app using AngularJS and $http.post -



javascript - Downloading a file in MVC app using AngularJS and $http.post -

any help welcomed , appreciated.

i have mvc action retries file content web service. action invoked angular service (located in services.js) using $http.post(action, model), , action returning filecontentresult object, contains byte array , content type.

public actionresult downloadresults(downloadresultsmodel downloadresultsmodel) { downloadresult = ... // retrieving file web service response.clearheaders(); response.addheader("content-disposition", string.format("attachment; filename={0}", downloadresult.filename)); response.bufferoutput = false; homecoming new filecontentresult(downloadresult.contents, downloadresult.contenttype); }

the issue i'm having browser not performing default behavior of handing file (for example, prompting open it, saving or cancel). action completed having content of file , file name (injected filecontentresult object), there s no response browser.

when i'm replacing post $window.location.href, , build uri myself, i'm hitting action , after completes browser handling file expected.

does can think of thought how finish 'post' expected?

thanks,

elad

i using below code download file, given file exist on server , client sending server total path of file...

as per requirement alter code specify path on server itself.

[httpget] public httpresponsemessage downloadfile(string filename) { filename = filename.replace("\\\\", "\\").replace("'", "").replace("\"", ""); if (!char.isletter(filename[0])) { filename = filename.substring(2); } var fileinfo = new fileinfo(filename); if (!fileinfo.exists) { throw new filenotfoundexception(fileinfo.name); } seek { var exceldata = file.readallbytes(filename); var result = new httpresponsemessage(httpstatuscode.ok); var stream = new memorystream(exceldata); result.content = new streamcontent(stream); result.content.headers.contenttype = new mediatypeheadervalue("application/octet-stream"); result.content.headers.contentdisposition = new contentdispositionheadervalue("attachment") { filename = fileinfo.name }; homecoming result; } grab (exception ex) { homecoming request.createresponse(httpstatuscode.expectationfailed, ex); } }

and on client side in angular:

var downloadfile = function (filename) { var ifr = document.createelement('iframe'); ifr.style.display = 'none'; document.body.appendchild(ifr); ifr.src = document.location.pathname + "api/gridapi/downloadfile?filename='" + escape(filename) + "'"; ifr.onload = function () { document.body.removechild(ifr); ifr = null; }; };

javascript asp.net-mvc angularjs asp.net-mvc-4 download

No comments:

Post a Comment