LoginSignup
1
1

More than 3 years have passed since last update.

JavaScriptを使い、ファイルをアップロードする

Last updated at Posted at 2020-04-28

概要

JavaScriptを使い、ファイルをアップロードする。
※実装サンプルはファイルを選択し、読み込みが完了した時点でアップロードするようになっているので注意

実装

※書き方が一部Reactになっているので読み替えてください

HTML側
<input type="file" accept=".png,.jpg" onChange={this.handleUpload} >
ファイル読み込み用のReaderを持つ
class Hoge extends React.Component {
    constructor(props) {
        super(props);
        this.reader = new FileReader();
    }

    // handleUpload()...実装は↓参照
    // eventMethod()...実装は↓参照
}
inputタグからファイルが選択された際にデータを格納する部分
handleUpload = e => {
    const target = e.target;

    // APIコール失敗→ファイル選択→キャンセル押下でundefinedがくるのでその対応
    if (target === undefined) { return; }
    // ファイルアップロード成功→再度、ファイル選択→キャンセル押下でtargetはあるけどfilesが無いでくるのでその対応
    if (target.files.length === 0) { return; }

    const uploadFileName = target.files[0].name; // ファイル名が欲しい場合のみ
    this.reader.readAsArrayBuffer(target.files[0]);

    // ファイルの読み込みが完了した際にイベント発火するので、
    // ファイルの読み込み完了後のハンドラ(eventMethod)を登録する
    this.reader.addEventListener('load', this.eventMethod);
}
アップロード処理(ファイル読み込み完了した際のハンドラ)
eventMethod = async e => {
    // ファイル読み込みのイベントリスナーをとりあえず削除
    this.reader.removeEventListener('load', this.eventMethod);
    const data = this.reader.result;

    // ファイルのアップロード処理
    try {
        await axios({ method: 'PUT', url: url, data: data, });
        // 事後処理
    } catch (error) {
        // 異常系
        console.error()
    }
};

参考

1
1
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
1