Rectangle 27 0

Your @Produces tag is conflicting with the type you set inline. If you both make them application/octet-stream I'd expect better results.

<div style="position:absolute;width:20px;height:20px;background:black" id="mydiv"><iframe id="hiddenDownloader" src="http:\localhost:8080\c:abc@abc.com#26 8 2012 13 5 49/gr1/output/test.csv"></iframe></div> This is what it gave me after i user iframe.src = data and changed the @produces to app/oct.. But it still did not ask me for the save download. I also changed the dataType: "application/octet-stream", in the ajax call

The Accepts header is only part of the puzzle. The browser reacts to the content-type of the response too.

jquery - Downloading csv file from server - Stack Overflow

jquery ajax rest
Rectangle 27 0

I guess using a temporary conventional form is a good workaround.

Download: function(item) {

        if (item) { var file = Content.files[(item ? $(item).attr('id').split('_')[1] : Content.selected.files[0])]; }

        else { if (Content.selected.files.length != 1 || Content.selected.folders.length != 0) { return; } var item = Content['files'][Content.selected.files[0]]; }

        if (file['encrypted']) {

            $.prompt({

                input: {

                    html: "Please enter the password to download this encrypted file: <br /><br /><input type='password' name='password' style='width:400px;' />",
                    buttons: { "Submit" : true },
                    persistent: false,

                    submit: function(event, value, message, form) {

                        $.prompt.goToState('pause');

                        $.post("?p=download&id="+file['id'], {

                            password: form.password, checking: true

                        }, function (response) {

                            if (response.ok) {  

                                $('body').append('<form id="encrypted_download" method="post" action="?p=download&id='+file['id']+'" style="display:none;"><input type="hidden" name="password" value="'+form.password+'" /><input type="hidden" name="checking" value="false" /></form>');

                                $('#encrypted_download').submit().remove(); $.prompt.close();

                            } else {

                                $.prompt.getStateContent('output').find('.jqimessage').html(response.result);

                                $.prompt.goToState('output');
                            }

                        },"JSON");  

                        return false;
                    }

                },

                pause: {

                    html: 'Please Wait... <img src="images/load_icon.gif" alt="" style="margin-bottom:-2px;margin-left:4px;height:12px;" />',
                    buttons: { },
                    persistent: true,

                },

                output: {

                    buttons: { Close: "Close" },
                    persistent: false
                }                   
            });

        } else {

            window.location.href = "?p=download&id="+file['id'];    
        }           
    },

php - posting data to server with jquery and downloading response as f...

php jquery http post download
Rectangle 27 0

I suggest replacing your ajax request with a hidden iframe, then when your server returns said 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's 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 );

An alternative would be to make it a two step process. Step 1 generates the file and returns a url, step 2 the user clicks download ( which would be an anchor tag pointing at said url).

asp.net - Download a file using jQuery after creating it in the server...

jquery asp.net ajax download
Rectangle 27 0

The reason you're getting a parse error is because jQuery has been told to interpret the return value of the AJAX call as JSON. The line dataType: "json" tells jQuery that you're expecting JSON from the server, so it can go ahead an run it through the JSON parser. However, your server is trying to return a data stream--something distinctly not JSON.

I'm not sure if what you're trying to do is possible. AJAX is not meant to be used for file-type or stream-based responses. It is meant to be used for XML (Asynchronous Javascript and XML) or JSON. Either way, AJAX is typically used to interpret a text-based response from the server, not stream-based. So what you're attempting to do with jQuery will probably not work.

Rather, why not offer a direct download link to the image. See the following question for a reference:

Force download file with jquery and asp.net server side function call ...

jquery asp.net
Rectangle 27 0

Two options are usually used but neither involves Ajax and jQuery won't be a great help either:

<iframe id="downloadFrame" style="display:none"></iframe>

When the download should start (you didn't mention how it is trigger), use Javascript (and possibly jQuery) to set the URL for the IFrame, which is something like /getInvoice/approvalId/123 in your case:

var iframe = document.getElementById("downloadFrame");
iframe .src = "/getInvoice/approvalId/123";

Setting the IFrame URL should trigger the browser to present the download dialog.

The second option is even simpler. Just navigate to the download URL. Once the browser figures out it's a MIME type that cannot be displayed, it will present a download dialog.

So when the download is triggered, execute the following Javascript code:

window.location.href = "/getInvoice/approvalId/123";

I'm not sure if all browser will reliably present a download dialog with PDF files. Some browsers might try to display it within the browser itself. The content disposition header is helpful but no guarantee.

I decided to not return byte[] with @ResponseBody. Now I set responses header <pre> private void setPdfHeaders(HttpServletResponse response, String shortFileName, File file) { response.setContentType("application/pdf"); response.setHeader("Content-disposition", "attachment; filename=" + shortFileName); response.setHeader("Content-Length", String.valueOf(file.length())); }</pre> then write stream to response OutputStream and user option 2 recommended by you.

How to download file from server using jQuery AJAX and Spring MVC 3 - ...

jquery spring-mvc download
Rectangle 27 0

I guess using a temporary conventional form is a good workaround.

Download: function(item) {

        if (item) { var file = Content.files[(item ? $(item).attr('id').split('_')[1] : Content.selected.files[0])]; }

        else { if (Content.selected.files.length != 1 || Content.selected.folders.length != 0) { return; } var item = Content['files'][Content.selected.files[0]]; }

        if (file['encrypted']) {

            $.prompt({

                input: {

                    html: "Please enter the password to download this encrypted file: <br /><br /><input type='password' name='password' style='width:400px;' />",
                    buttons: { "Submit" : true },
                    persistent: false,

                    submit: function(event, value, message, form) {

                        $.prompt.goToState('pause');

                        $.post("?p=download&id="+file['id'], {

                            password: form.password, checking: true

                        }, function (response) {

                            if (response.ok) {  

                                $('body').append('<form id="encrypted_download" method="post" action="?p=download&id='+file['id']+'" style="display:none;"><input type="hidden" name="password" value="'+form.password+'" /><input type="hidden" name="checking" value="false" /></form>');

                                $('#encrypted_download').submit().remove(); $.prompt.close();

                            } else {

                                $.prompt.getStateContent('output').find('.jqimessage').html(response.result);

                                $.prompt.goToState('output');
                            }

                        },"JSON");  

                        return false;
                    }

                },

                pause: {

                    html: 'Please Wait... <img src="images/load_icon.gif" alt="" style="margin-bottom:-2px;margin-left:4px;height:12px;" />',
                    buttons: { },
                    persistent: true,

                },

                output: {

                    buttons: { Close: "Close" },
                    persistent: false
                }                   
            });

        } else {

            window.location.href = "?p=download&id="+file['id'];    
        }           
    },

php - posting data to server with jquery and downloading response as f...

php jquery http post download
Rectangle 27 0

If you're wanting to use the jquery plugin for an enhanced user experience, you cant initiate the download from the server. Best bet in that case would be to generate the file on the server and have that method return the path to the file. Then just dl using the plugin.

$('#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);
}

asp.net - Download a file using jQuery after creating it in the server...

jquery asp.net ajax download
Rectangle 27 0

You can't do that so straight forward because the response is not sent to the browser.

As an alternative you could do 2 requests like that:

public ActionResult Method([Bind(Prefix = "Id")] Guid id)
{
    //Long work

    string newGuid = Guid.NewGuid().ToString();
    TempData[newGuid] = data;

    return Content(newGuid);
}

public ActionResult Download(string guid)
{
    byte[] data = (byte[])TempData[guid];

    return File(data, "application/pdf", "teste.pdf");
}
function DownloadFile(id) {
    var url = '@Url.Action("Method")';
    $("#divLoading").show();
    $.get(url, 
                function (data, textStatus, jqXHR)
                {
                    $("#divLoading").hide();
                    window.location.href = '@Url.Action("Download")' 
                                            + '?guid=' + data;
                }
           );
}

asp.net - How to make jQuery loader before server responding for downl...

jquery asp.net razor download loader
Rectangle 27 0

After a lot of RnD I think I have found the solution to my problem. This might not be the ideal solution and please let me know if there are any major problems with it.

Basically I tried accessing my file on the server and could only access it from the docroot folder (PATH = C:\glassfish3\glassfish\domains\domain1\docroot). So I realized that I must copy my file from wherever on the server to this location. I did that in the Web service. I read somewhere and was trying to send the file itself from the web service. That was wrong after this change I only sent back a plain text with the path relative to docroot.

Then there was another setback as my file had to be within a folder and the folder name contained a # character. It seems # is not allowed and the iframe just wouldn't ask me for the downloading!!

Now I have modified my code as follows : REST:

Hoping someone finds it useful!! Thanks for the inputs!

there is a problem with the downloaded file. The file is not actually returned in my solution only the path from docroot onwards is. Sometimes it gives a character encoding error and does not download the file. "The character encoding of a framed document was not declared. The document may appear different if viewed without the document framing it." This could be due to not setting the contenttype of the files data. Any suggestions??

jquery - Downloading csv file from server - Stack Overflow

jquery ajax rest
Rectangle 27 0

Maybe a better strategy would be to use jQuery to build a new <A> link on the page that'll reference this same URL, and insert this new element at a appropriate place in the DOM. That being done, maybe jQuery can even then click it for the user, initiating the download.

Unfortunately for obvious security reasons you cannot programmatically click a link.

How to download file from server using jQuery AJAX and Spring MVC 3 - ...

jquery spring-mvc download
Rectangle 27 0

Obviously, Django doesn't know URL:/root/ivenv/test_case_tool/docs/newProjectFoldr.tar where it is. So you get a 404 error(NOT FOUND).

You could write a corresponding url in urls.py or put the file in STATIC_ROOT folder(see your settings.py, add STATIC_ROOT = 'static' and STATIC_URL='/static/' if without), Then you could visit.

put the file in appname/static/ folder, when DEBUG=True in settings.py, Django will find it automatically.

visit {{ STATIC_URL }}/newProjectFoldr.tar to download the file. when deploy, run python manage.py collectstatic to collect static files to STATIC_ROOT folder, when DEBUG=False django doesn't server static files, you can use Apache.

javascript - How to download file from server to client in django on b...

javascript django
Rectangle 27 0

@GetMapping("/downloadFile")
    public void download(HttpServletRequest request, HttpServletResponse response)throws Exception{
        try {
            fileName=fileName.replace(" ", "_");
            File file = new File(outputPath+ fileName);
            FileInputStream fis = new FileInputStream(file);
            Path source = Paths.get(outputPath+ fileName); 
            String contentType=Files.probeContentType(source);
            response.setContentType(contentType);
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment; filename="+fileName);
            FileCopyUtils.copy(fis, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

The above code gave me the result!

jquery - Why after downloading Excel (xlsx) file from server, File is ...

jquery excel spring
Rectangle 27 0

$("#btnDownload").click(function () {
        $.support.cors = true;                    
        $.fileDownload("http://localhost/fileDownload.txt", {  
               successCallback: function (url) {  
                   alert('You just got a file download dialog or ribbon for this URL :' + url); 
                   },  
                   failCallback: function (html, url) {    
                   alert('Your file download just failed for this URL:' + url + '\r\n' +     
                                          'Here was the resulting error HTML: \r\n' + html);    
                   }
        }                      

});

I think the first ajax request is unecessary.

Because this makes the request also: $.fileDownload

Server code: In the demo (MVC3 app) he uses the controller to send the file from the server to the client. Inside the controller there is a FilePathResult type function. Try this way, maybe it works, but I can't try it now.

public FilePathResult GetData(string value)
{  
    return File("~/fileDownload.txt", "text/plain", "fileDownload.txt");
}

this method is not working for me, I get the same message

do you think the server code is correct

try to modify the signature: public void GetData(object value)

no this is not possible, because the parameters must be string value

I think it's correct, I'had similar issue with soap webservice, and if you dont pass the correct type of object from javascript to the service, it will fails, and do not hit the server code. with object you can receive any type of parameter. Just modify it and try, and if it's good, we can find out what to do.

asp.net - download file from server with the jQuery fileDownload plugi...

jquery asp.net webforms download