簡體   English   中英

如何在使用JavaScript單擊按鈕時更改文件名並下載

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

我有一個用JavaScript創建的下載按鈕鏈接到特定文件。

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

我必須在下載之前將文件image1重命名為image2 ,所以我使用:

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

問題是創建了2個下載按鈕(HTML5下載屬性再創建1個)。

有沒有辦法使用JavaScript創建的相同按鈕,並參考下載屬性?

我不知道你在做什么Brad Christie,

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

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

在這里,您有一個要下載的元素,您將獲得該元素並更改其下載屬性。

我不是100%肯定它會工作,但我之前做過類似的事情來下載資源並使用javascript重命名它。 但是,它確實意味着資源必須與頁面位於同一個域中,否則您將遇到跨域安全問題。 另外,請原諒我正在使用jQuery,但如果你不需要,我會讓你查看如何進行跨瀏覽器的AJAX調用。

照這樣說:

<!-- 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>

沒有測試,但應該工作。 基本上,您可以使用jQuery獲取資源並將其存儲到具有指定名稱的Blob中。 如果能夠這樣做,則鏈接現在變為具有提供名稱的自定義命名blob資源。 如果不能保留默認功能,用戶需要自己命名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM