SKay
SKay

Reputation: 147

javascript : download file from server : open file dialog to choose folder to save file

Want to download a file , the "save folder dialog' should pop up to chose the folder where to save the file.

I tried with window.location, window.location.assign, widow.open functions. Everything leads to opening a fresh page! and cant see any "save folder dialog" popped up!

downloading file name is with extension .cfg, the file can be either binary or Json(text file). Will there be any difference if the file being binary or text?

$( document ).ready(function() {

  $("#DownloadFile").click(function() {
    // // hope the server sets Content-Disposition: attachment!
    var 	urlData= window.location.protocol + "//" +       window.location.host + "/" + "download/testdown.cfg";
    alert("download file: " + urlData);
    retval = fileExists(urlData);
    if(retval) {
      alert("file exists !!");
      window.location = 'download/testdown.cfg';
      // window.location.assign(urlData);
      // window.open(urlData, 'Download');  

    }else{
      alert("File not exists !");
    }
  });





  function fileExists(url) {
    alert(" url : " + url);
    if(url){
      alert(" url : " + url);
      var req = new XMLHttpRequest();
      req.open('HEAD', url, false);
      req.send();
      // return req.status==200;
      return true;
    } else {
      return false;
    }
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed table-bordered table-striped volumes tabcenter" 
       style="align:center; margin:5px; width:98%">

  <tbody>
    <tr>
      <td>
        <div class="row">
          <h1>Choose File Type</h1>
          <label class="radio-inline">
            <input name="radioGroup" id="radio1" value="option1" type="radio"> Binary Data
          </label>
          <label class="radio-inline">
            <input name="radioGroup" id="radio2" value="option2" checked="" type="radio"> Json Data
          </label>

        </div>  
      </td>

      <td > 
        <button type="submit" id="DownloadFile" >Download!</button>
      </td>
    </tr>
  </tbody>
</table>

Upvotes: 2

Views: 4983

Answers (1)

Mykola Borysyuk
Mykola Borysyuk

Reputation: 3411

For security reasons JavaScript in browser are not allowed to have access to user computer. So you just need to make ways in standard way. Button sends request to server and it return correct headers which will save file in special directory. Also read this answer.

How can I read the client's machine/computer name from the browser?

Also read this answer.

Local file access with javascript

Upvotes: 1

Related Questions