簡體   English   中英

從url下載pdf,將其保存在文件中,壓縮然后下載zip

[英]Pdf download from url, save it in a file, zip then download the zip

一直在使用jszip來創建和下載zip文件。 我可以單獨下載pdf文件。 但我想將這些pdf下載到zip文件夾中,然后下載zip文件。

用於下載pdf的代碼段:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       window.location.href = "pdf_url"
    }
};
xhttp.open("GET", "pdf_url");
xhttp.send();

添加zip api:

    var zip = new JSZip();
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
           window.location.href = "pdf_url"
           zip.file("file_name", pdf_url_content);
        }
    };
    xhttp.open("GET", "pdf_url");
    xhttp.send();

創建zip:

  zip.generateAsync({type:"blob"})
    .then(function callback(blob) {
      saveAs(blob, "example.zip");
    }

pdf_url_content應該包含url的內容。 如何閱讀該內容? 我嘗試使用jszip-utils。 無法繼續。 任何幫助,將不勝感激。

提前致謝。

首先,壓縮pdf是沒用的,因為用戶將使用xmlhttprequest將其壓縮下載,然后壓縮,因此他必須兩次下載文件。

無論如何,我回答了你的消息

您應該將正確的內容類型設置為xmlhttprequest ,將responseTypeblob 然后,您可以使用onreadstatechange回調中的屬性response來訪問pdf的內容

var zip = new JSZip();
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "pdf_url");
xhttp.responseType = "blob";
xhttp.setRequestHeader("Content-type", "application/pdf");
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       zip.file("file_name", xhttp.response);
       zip.generateAsync({type:"blob"})
          .then(function(blob) {
               saveAs(blob, "example.zip");
          });
    }
};

xhttp.send();

請注意,下載部分需要FileSaver.jssaveAs函數)。

暫無
暫無

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

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