0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Vue】フォームのファイルをBase64エンコードした文字列としてAPIに送信する

Last updated at Posted at 2024-01-30

FileReader.readAsDataURL() を利用する。
※ readAsDataURL()でbase64エンコードされた文字列は先頭に data:*/*;base64, という文字列が付加されるので、base64文字列のみを取得したい場合はこの接頭辞を削除しなければならない。

<template>
<div>
    <form ref="form" @submit.prevent="submit">
      <div>
        <input id="js_file" type="file">
      </div> 
      <div>
        <input type="submit" value="送信">
      </div>
    </form>
</div>
</template>

<script setup lang="ts">
import { InputHTMLAttributes, ref } from "vue"

class Common {
  /**
   * blobオブジェクトを引数にとってBase64エンコードされた内容を返す
   */
  public static readAsBase64(file: Blob): Promise<string> {
    const promise = new Promise((resolve, reject) => {
      let reader = new FileReader();
      reader.onload = () => {
        resolve(reader.result)
      }
      reader.onerror = reject
      reader.readAsDataURL(file)
    }).then((dataUrl): string => {
      if (typeof dataUrl === "string") {
        return dataUrl.replace(/data:.*\/.*;base64,/, '');
      }
      throw new Error("dataUrl is not string")
    })
    return promise
  }
}

async function submit(event: Event) {
  // ファイルの中身をBase64エンコードした文字列を取得
  let file = document.getElementById("js_file").files[0]
  let content = await Common.readAsBase64(file)
  console.log(content)
  let res = await fetch("http://example.co.jp/file/", {
    method: "POST",
    body: JSON.stringify({
      "content": content,
    })
  })
  console.log(res)
}
</script>
0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?