开发者

Downloading file via MVC controller

I am modifying some MVC code for a project we took over, I don't have tons of MVC experience.

The application displays a table full of items that can be selected. These items are passed to a controller which would create a download file containing those items. Previously, the items were passed via QueryString, which is fine unless LOTS of choices are made. IE has a URL limit of ~2048 characters, each item is ~30 characters long so downloading 70 items would cause issues (truncated query string).

I modified the javascript to pass the data to the controller via Ajax. This is working fine, but now when the data is returned to the page, there is no download window being displayed.

the old javascript looked like this:

 function doDownload(url)
 {
     var data = AppendItems();
     url = url;
     var mybars = "directories=no,location=no,menubar=no,status=no";
     mybars += ",titlebar='',toolbar=no,alwaysraised=yes,maximize=no";
     var myoptions = "scrollbars=yes,fullscreen,resizable=yes";
     var myfeatures = mybars + "," + myoptions;


     if (!newWindow || newWindow.closed()) {
         newWindow = window.open(url + data, "DownloadIncomingFile", myfeatures);
         newWindow.focus();
     }
 }

I've turned that list bit into:

$.ajax({
    type: "POST",
    url: "DownloadIncomingWires/Download",
    data: { 
        filePaths: filePaths,
        completeStatus: completeStatus 
    },
    traditional: true
});

This is successfully sending the data TO the controller, I just don't know what to do on the开发者_Python百科 VIEW side to have the typical "DOWNLOAD" window be displayed.

Whenever I add the window.open piece, I get a 404 error. Without it, I get nothing.


if you load this per ajax you wont get an download window. because jquery handles the answered document internal.

the window.open method is for my reason not the right way. because the user see an popup window what is not needed.

my solution is to set an iframe with the URL of your Download-File (Controller)

so in jQuery:

doDownload = function(url) {
   var dframe = jQuery('#downloadframe');
   if(dframe.length < 0) {
      jQuery('body').append('<iframe style="position:absolute; left:-10000px; visible:hidden;" src="'+url+'" id="downloadframe" />');
   } else {
      dframe.attr('src',url);
   }
};

Your controller have to set the Content-type to: application/force-download or to the Content-type of the delivered File.

Good Luck

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜