LoginSignup
1
1

More than 1 year has passed since last update.

【JavaScript】指定したフォルダにURLリソースを取得する

Last updated at Posted at 2021-06-16

はじめに

FileSystemAccessとは

ユーザーのデバイス上のファイルやフォルダーへの変更を直接読み取ったり保存したりするためのAPIです。

公式githubレポジトリ : https://github.com/WICG/file-system-access

GoogleChrome, Edge, OperaなどのChronium系ブラウザにしか対応していませんので使用する際にはご注意ください。

参考:Can I use file system access?

基本的な使用方法について

以下の記事が参考になります。
Native File System APIを試してみる

コード

App.jsx
import { useState } from 'react'

const App = () => {
  const [imgUrl, setImgUrl] = useState('')
  const [dirText, setDirText] = useState('')
  const [dirHandle, setDirHandle] = useState(null)

  async function openDir() {
    try {
      const handle = await window.showDirectoryPicker()
      setDirHandle(handle)
      setDirText(handle.name)
    } catch (e) {}
  }

  async function saveImg() {
    if (!imgUrl) return false
    if (dirHandle) {
      save(imgUrl)
    } else {
      alert('保存先を選択してください')
    }
  }

  async function save(url) {
    const fileHandle = await dirHandle.getFileHandle(`test.png`, {
      create: true,
    })
    const writable = await fileHandle.createWritable()
    const response = await fetch(url)
    await response.body.pipeTo(writable)
  }

  const onChangeImgUrl = (e) => {
    setImgUrl(e.target.value)
  }

  return (
    <div>
      <button className="directory" type="button" onClick={openDir}>
        Open directory
      </button>
      <pre className="directory">{dirText}</pre>
      <br />
      <input type="url" value={imgUrl} onChange={onChangeImgUrl} />
      <button onClick={saveImg}>保存</button>
      <br />
      {imgUrl && <img src={imgUrl} alt="" id="img" />}
    </div>
  )
}

export default App

コード解説

フォルダの指定

app.jsx
  async function openDir() {
    try {
      const handle = await window.showDirectoryPicker()
      setDirHandle(handle)
      setDirText(handle.name)
    } catch (e) {}
  }

window.showDirectoryPickerでフォルダを指定します。
フォルダの選択時にキャンセルを行うと例外をスローするのでtry catchを書いています。

ファイルの保存

app.jsx
  async function save(url) {
    const fileHandle = await dirHandle.getFileHandle(`test.png`, {
      create: true,
    })
    const writable = await fileHandle.createWritable()
    const response = await fetch(url)
    await response.body.pipeTo(writable)
  }

dirHandlewindow.showDirectoryPicker()で取得したフォルダ情報です。
ファイルハンドラーに書き込むためにcreateWritableを使用します
dirHandle.getFileHandleでは取得したフォルダに対して書き込むファイルを生成しています。test.pngと画像ファイルが前提となっていますが、使う際はファイル名、拡張子名などはURLリソースに応じて指定できるようにしてください。

fetchでURLリソースに対してアクセスをし、pipeToにて書き込みを行っています。

参考

The File System Access API: simplifying access to local files
File System Access API - Web APIs | MDN
W3C File System Access

1
1
0

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
1