LoginSignup
1
0

More than 3 years have passed since last update.

JavaScriptを使い、multipart/form-dataでファイルをアップロードする

Last updated at Posted at 2020-04-28

概要

JavaScriptを使い、multipart/form-dataでファイルをアップロードする。

実装

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

HTML側
<input type="file" accept=".png,.jpg" onChange={this.handleUpload} >
inputタグからファイルが選択された際にデータを格納する部分
handleUpload = e => {
    const target = e.target.files[0];
    // ファイル選択→キャンセル押下でundefinedがくるのでその対応
    if (target === undefined) { return; }
    this.data = target; // this.dataはデータを格納する先なら何でも可(thisじゃなくていい)
}
実際にデータをアップロードする部分(handleUpload()が実行されている前提)
doUpload = async () => {
    let form = new FormData();
    form.append('image', this.data); // 'image'は multipart の name

    try {
        const res = await axios.post(url, form);
        // 以降は必要な事後処理を書くこと
    catch (error) {
        // 異常系
        console.error(error)
    }
}

参考

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