1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでファイルをダウンロードする方法

Last updated at Posted at 2024-02-17

認証が必要なAPIなどにアクセスして、レスポンスをファイルとしてダウンロードしたいときのやり方。

async function download(url, filename) {
  // ダウンロードしたいURLにアクセス
  let res = await fetch(url, {
    method: 'GET',
    headers: { 'Authorization': "xxxxxxxxxxxxxxxxxxx" },
  }).catch((err) => err.data)
  
  if (res.status == 200) {
    // blobとして内容を読み出す
    const content = await res.blob()
    // オブジェクトURLを生成
    const objectUrl = (window.URL || window.webkitURL).createObjectURL(content)
    // オブジェクトURLをhref属性に設定したaタグを作成
    const a = document.createElement('a')
    a.href = objectUrl
    a.download = filename
    // aタグをクリック
    a.click()
  }
}

var url = "https://www.yahoo.co.jp/"
var filename = "index.html"
await download(url, filename)
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?