简体   繁体   中英

Javascript change name of file on download

The files on the server are renamed with a random id and the original name is stored in the database when they are uploaded using php for security reasons (client's request). For the files to be downloaded I was just using a page listing the files using this

<li>
    <a href="path_to_file/temp_name" download="name_from_db">name_from_db</a>
</li>

and that worked well but now the client would like a dialogue box asking for the name of the downloader before the file download begins...

<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
});

This works well except the file is downloaded using the random id for the name rather than the original name stored in the database. How can I get the file to be downloaded using the orig_name value?

Ok, sussed it...

in the ajax success I did this...

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

This triggers the file download and changes the file name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM