web-dev-qa-db-ja.com

Axiosでバイナリファイルをダウンロードする

たとえば、PDFファイルのダウンロード:

axios.get('/file.pdf', {
      responseType: 'arraybuffer',
      headers: {
        'Accept': 'application/pdf'
      }
}).then(response => {
    const blob = new Blob([response.data], {
      type: 'application/pdf',
    });
    FileSaver.saveAs(blob, 'file.pdf');
});

ダウンロードしたファイルの内容は次のとおりです。

[object Object]

ここで何が問題になっていますか?バイナリデータがファイルに保存されないのはなぜですか?

16
Anton Pelykh

以下のように(FileSaverを使用せずに)実行可能な要旨を作成できました。

axios.get("http://my-server:8080/reports/my-sample-report/",
        {
            responseType: 'arraybuffer',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/pdf'
            }
        })
        .then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'file.pdf'); //or any other extension
            document.body.appendChild(link);
            link.click();
        })
        .catch((error) => console.log(error));

それが役に立てば幸い。

乾杯!

3
Nayab Siddiqui
     Nova.request().get(`api`,{responseType: 'arraybuffer'})
                    .then(response => {
                        console.log("sa", response)
                        const url = window.URL.createObjectURL(new Blob([response.data]))
                        const link = document.createElement('a')
                        link.href = url
                        link.setAttribute('download', file_name)
                        document.body.appendChild(link)
                        link.click()

                    });
                    
                    

私はdisのように使用していますが、ダウンロードすると写真のソースファイルが見つからないので

0
zensine

Response.dataは単なる通常のオブジェクトのようです。 Blobは最初の引数「ArrayBuffer、ArrayBufferView、Blob、またはDOMStringオブジェクトの配列」を取ります。

JSON.stringifyでラップしてみてください

const blob = new Blob([JSON.stringify(response.data)]

次に、DOMString要件を満たします。

0
maxLatoche