Upload a file using jQuery after creating it on the server

When I push the button on the client side, I want to call the open static web method on the server side using AJAX. The static method will create the corresponding file. After creating the file, I need to upload it to the client desktop. I found a jQuery plugin to load using jQuery , but still have not been able to implement it. I know that using this plugin also requires writing a cookie so that it knows that the download is complete. Where can I put this code on the server? After creating the file? I would be very happy if someone could show me a sample in this scenario, possibly at jsfiddle.net

+4
source share
2 answers

I suggest replacing your ajax request with a hidden iframe, and then when your server returns the specified file, it will automatically ask the user to download it.

//name of iframe var strName = ("uploader" + (new Date()).getTime()); // the iframe var jFrame = $( "<iframe name=\"" + strName + "\" src=\"about:blank\" />" ).css( "display", "none" ); jFrame.load(function( objEvent ){ // at this point the user should have been asked to download a file. // Remove the iFrame from the document. // Because FireFox has some issues with // "Infinite thinking", let put a small // delay on the frame removal. setTimeout(function(){ jFrame.remove(); },100); }); var form = $('<form>').attr( "action", "upload_act.cfm" ) .attr( "method", "post" ) .attr( "enctype", "multipart/form-data" ) .attr( "encoding", "multipart/form-data" ) .attr( "target", strName ); form.append('<input type="hidden" name="somename">').val("someval"); $( "body:first" ).append( jFrame, form ); 

(The above code was originally adapted from http://www.bennadel.com/blog/1244-ColdFusion-jQuery-And-AJAX-File-Upload-Demo.htm )

An alternative would be to make this a two-step process. Step 1 generates the file and returns the URL, step 2, which the user clicks on the download (this will be an anchor tag pointing to the specified URL).

+2
source

If you want to use the jquery plugin for the advanced user interface, you cannot initiate a download from the server. The best thing in this case would be to generate a file on the server, and this method will return the path to the file. Then just dl using the plugin.

Example:

 $('#btnID').click(function(){ $.ajax({ type: "POST", url: "/your_webmethod_url", data: "{'webmethodParam1':'val1','webmethodParam2':'val2'}", contentType: "application/json; charset=utf-8", dataType: "json", success: fileGenerated, error: fileNotGenerated }); }); function fileGenerated(data, textStatus, jqXHR){ //this is the success callback method. start download automatically using the plugin $.fileDownload(data.d); //returned data from webmethod goes in data.d } function fileNotGenerated(jqXHR, textStatus, errorThrown){ //this is the error callback method. do something to handle the error alert(errorThrown); } 
+1
source

All Articles