简体   繁体   中英

How to change a file name and download it when a button is clicked using JavaScript

I have one download button created in JavaScript that links to particular file.

var strDownloadButton = "<br/><INPUT type="button" value="Download" onclick="add()"/>"
window.location.href = "/images/image1.jpg";

I have to rename the file image1 to image2 before downloading, so I use:

<a href="/images/image1.jpg" download="image2" >Download</a> 

The problem is that there are 2 download buttons created (HTML5 download attribute created 1 more).

Is there any way to use the same button created by JavaScript, and refer into download attribute?

I have no idea what are you doing Brad Christie,

<a id="download" href="Chrysanthemum.jpg" download="image2" >Download</a>

document.getElementById("download").setAttribute("download", "image3")

here, you have an element that you want to download, you get the element and change its download attribute.

I'm not 100% sure it'll work, but I've done something like this before to download a resource and rename it using javascript. It does, however, mean the resource has to be on the same domain as the page otherwise you will run into a cross-domain security issue. Also, please excuse the fact that I'm using jQuery, but if you need to go without I'll let you look up how to make a cross-browser AJAX call.

With that said:

<!-- your anchor decorated with data-saveas -->
<a href="/some/image.jpg" data-saveas="image2.jpg">Download</a>

<!-- wiring it up using jQuery/AJAX/Blob -->
<script type="text/javascript">
  // Helper to convert AJAX response in to a BLOB
  function dataToBlob(data, mimeString){
    // convert data to ArrayBuffer
    var buffer = new Int8Array(new ArrayBuffer(data.length));
    for (var i = 0; i < data.length; i++){
      buffer[i] = data.charCodeAt(i) & 0xff;
    }

    // http://stackoverflow.com/a/15302872/298053
    try {
      return new Blob([buffer],{type:mimeString});
    } catch (e1) {
      try {
        var BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
        if (e.name == 'TypeError' && window.BlobBuilder){
          bb = new BlobBuilder();
          bb.append([buffer.buffer]);
          return bb.getBlob(mimeString);
        } else if (e.name == 'InvalidStateError'){
          return new Blob([buffer.buffer],{type:mimeString});
        }
      } catch (e2) {
      }
    }
    return null;
  }

  // iterate over all the items that are marked as saveas
  $('a[data-saveas]').each(function(){
    var $this = $(this);

    // Get the actual path and the destined name
    var target = $this.prop('href'),
        saveas = $this.data('saveas');

    // make an ajax call to retrieve the resource
    $.ajax({
      url: target,
      type: 'GET',
      mimeType: 'text/plain; charset=x-user-defined'
    }).done(function(data, textStatus, jqXHR){
      var mimeString = jqXHR.getResponseHeader('Content-Type'),
          blob = dataToBlob(data, mimeString);
      if (blob){
        // now modfy the anchor to use the blob instead of the default href
        var filename = saveas,
            href = (window.webkitURL || window.URL).createObjectURL(blob);
        $this.prop({
          'download': saveas,
          'href': href,
          'draggable': true
        }).data({
          'downloadurl': [mimeString, filename, href].join(':')
        });
      }
    });
  });
</script>

Not tested, but should work. Basically, you can go fetch the resource using jQuery and store it in to a blob with an assigned name. If it's able to do so, the link now becomes a custom-named blob resource with the provided name. if it can't the default functionality is retained and the user needs to name it his/herself.

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