asp.net mvc - How to download a file using MVC & jQuery -
i hope not re-posting same issue, because think common issue , yes have searched forum, found suggestions didn't work me.
i trying implement download functionality using mvc & jquery. have button, , when click on button want download file without refreshing current view. if there error want show error in alert. button’s onclick() event configured download() function.
here code
<button onclick="download(123);">download</button> function download(fileid) { window.location = "/users/mycontroller/downloadfile?fileid="+ fileid; } the above function works. see download popup window. if there error connecting url, or there exception inside controller on server. in such case want show alert error message. thought of using jquery ajax can handle success & error events. change javascript function use ajax call below doesn’t work. makes call server, see controller gets executed. don’t see download popup window.
function download(fileid) { var datatopost = { fileid: fileid}; $.ajax({ type: 'post', data: json.stringify(datatopost), url: "/users/mycontroller/downloadfile", contenttype: 'application/json; charset=utf-8', success: function (result) { // don’t want set window.location here because event gets fired after server call. setting here make 1 more server call download file. }, error: function (xhr, ajaxoptions, thrownerror) { // how exception message here? } }) controller code
public actionresult downloadfile(int fileid) { try { var filepath = getfilepath(fileid); var fp = new filepathresult(filepath, "application/octet-stream"); fp.filedownloadname = "test.xlsx"; return fp; } catch (filenotfoundexception ex) { throw new exception("cound not file requested file."); } catch (exception ex) { throw new exception("there problem downloading file"); } }
unfortunately, can't use $.ajax download file, it's limitation of html/javascript. there hacks involve downloading file hidden iframe , using cookie track whether or not downloaded simulate ajax, however. personally, use jquery plugin, http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/ web page gives explanation of it's doing (using iframe , cookie). plugin gives handlers can display message "the download has started" when begins, , handlers fire on success , failure. implement hidden iframe logic yourself, i've found plugin super easy use personally.
there sample on page shows how set cookie in mvc well.
Comments
Post a Comment