How to force browser download dialog

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • swand9
    New Member
    • Nov 2009
    • 2

    How to force browser download dialog

    Hi,
    I need to downlad a server side generated csv file with Javascript.
    I need to send the login name and password and I don't want to use GET as I want to avoid a visible password in the URL.
    Further, my displayed HTML page should not reload.

    This is what I have tried:

    1) Ajax:
    Code:
    var link = "http://.....";
    var base = base64Encode("k320i:xxxxx");
    var xhr = new XMLHttpRequest();
      var async = false;
      xhr.open("POST", link, async);
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhr.setRequestHeader("Authorization", "Basic " + base);
      xhr.send("a=XXXX");
    -> This works fine, but no download dialog pops up in the browser, the response arrives as xhr.responseTex t

    2) A hidden POST Form
    Code:
    <form id="downloadFormPOST" action="http://localhost:8080/io/rest/stat/k320i/2008-10-19/2009-10-20T12:00/test.csv" method="post" target="_blank">
      <input type="hidden" name="_loginName" value="k320i">
      <input type="hidden" name="_password" value="xxxx">
    </form>
    And trigger it like this:
    Code:
    var downloadForm = window.document.forms['downloadFormPOST'];
        downloadForm.submit();
    But now the password is not transmitted
    Can I somehow attach Basic authentication to above form?

    Question: What is the correct approach?


    Thanks
    Marcel
    Last edited by Dormilich; Nov 17 '09, 01:05 PM. Reason: Please use [code] tags when posting code
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    What's the header set to for the CSV page? If you make a normal GET request, does it work?

    Comment

    • swand9
      New Member
      • Nov 2009
      • 2

      #3
      How to force browser download dialog: Partly resolved

      Hi again,

      the "2) A hidden POST Form" works!
      It was my mistake on server side (a Java REST servlet) during parsing the form data.

      But "1) Ajax" I didn't find a way to popup the browser download dialog during a Ajax response inside the browser (via Javascript)

      So I'm using now solution 2).

      I'm still curious: How to attach HTTP basic authentication to the <form> markup?

      thanks
      Marcel

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        http://www.peej.co.uk/articles/http-...tml-forms.html - a bit experimental, but should help.

        Comment

        Working...