Javascript在下载时更改文件名

时间:2017-06-10 12:58:26

标签: javascript jquery

服务器上的文件使用随机ID重命名,出于安全原因(客户端的请求)使用php上传原始名称时,原始名称将存储在数据库中。对于要下载的文件,我只是使用一个列出使用此文件的文件的页面

<li>
   <span id="file_id" class="image_list">name_from_db</span>
   <input type="hidden" name="file_path" value="path_to_file/temp_name" >
</li>

$('#results_table_div').on('click', '.image_list', function(){
    var file_id = $(this).attr('id');
    var path = $(this).siblings('input[name="file_path"]').val();
    swal({
      title: 'Please enter you name',
      input: 'text',
      type: 'question',
      showCancelButton: true,
      inputValidator: function (value) {
        return new Promise(function (resolve, reject) {
          if (value) {
            resolve()
          } else {
            reject('Please enter your name to download the file')
          }
        })
      }
    }).then(function (result) {
        jQuery.ajax({
        type: "POST",
        url: "ajax/log_download.php",
        dataType: "json",
        data: 'file_id='+file_id+'&name='+result,
        cache: false,
        success: function(response) {
            if(response.success === 'yes'){
                var orig_name = (response.name_from_db);
                window.location.href=path;
            }
        }
    });//end ajax
});

并且运行良好但现在客户端想要一个对话框,在文件下载开始之前询问下载程序的名称...

orig_name

除了使用名称的随机ID而不是存储在数据库中的原始名称下载文件之外,这种方法很有效。如何使用TAG TYPE=SELECT ... CONTENT=(the second option)值来下载文件?

1 个答案:

答案 0 :(得分:0)

好的,怀疑它......

在ajax的成功中,我做到了这一点......

if(response.result === 'success'){
    var orig_name = (response.name_from_db);
    var downloadLink = document.createElement('a');
    downloadLink.href = path;
    downloadLink.download = orig_name;
    document.body.appendChild(downloadLink);
    downloadLink.click();
}

这会触发文件下载并更改文件名

相关问题