从服务器下载文件:打开文件对话框选择保存文件的文件夹

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

本文关键字:文件 保存文件 选择 文件夹 对话框 服务器 下载      更新时间:2023-09-26

下载文件时,会弹出"保存文件夹"对话框,选择保存文件的文件夹

我尝试了window.location, window.location.assign, widow.open函数。一切都是为了翻开新的一页!并且看不到弹出任何"保存文件夹对话框"!

下载文件名扩展名为.cfg,文件可以是二进制或Json(文本文件)。如果文件是二进制文件还是文本文件,会有什么区别吗?

$( 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>

出于安全原因,浏览器中的JavaScript不允许访问用户计算机。所以你只需要用标准的方法。按钮向服务器发送请求,它返回正确的头,将文件保存在特殊目录中。也看看这个答案。

如何从浏览器读取客户端's机器/计算机名?

也看这个答案。

使用javascript访问本地文件