9
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jpgやmp3をブラウザで開かずにダウンロード(ファイル保存)させるJavaScript

Last updated at Posted at 2017-09-30

着地シンプルだったけどドハマりしたのでメモしておく。

  • ファイル保存はHTML5の <a href="" download=""></a> でも一見できそうだが、jpgやmp3はブラウザ上で開いてしまうのでNG
  • HTML5の saveAs() は各ブラウザ対応が違いすぎて死んだのでFileSaverというライブラリに任せたかった
  • MINE_TYPEの指定不要っぽい?(ファイル形式によっては必須かもしれない)
  • 対象ファイルをURL経由で取得する際、axiosの場合はresponseType: 'blob'が必須だった
// ES2015
import axios from 'axios'
import FileSaver from 'file-saver'

return axios.get('https://hogefuga.com/input_filename.mp3', {responseType: 'blob'})
  .then((res)=>{
    const blob = res.data
    FileSaver.saveAs(blob, 'download_filename.mp3')
  })
9
12
2

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
9
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?