2
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?

More than 1 year has passed since last update.

【Javascript/Typescript】fetch APIでmultipart/form-dataを送信したい(備忘録)

Posted at

結論

Content-Typeに値を設定しない & FormDataオブジェクトをbodyにセット
FormDataオブジェクトをbodyにセットすれば、fetch APIが予期に計らって、HTTPリクエストを作ってくれるようです。

サンプルコード

※ TSで書いてるので型まわりのコードも含まれています。

type contentProps = {
	title: string,
	description: string,
	image: Blob | null
}

const CreateContent = async (props: contentProps) => {

	const headers = new Headers({
      // 略
	})

	const body = new FormData()
	body.append("title", props.title)
	body.append("description", props.description)
	if (props.image != null) {
		body.append("image", props.image, 'image.jpg')
	}

	const data: RequestInit = {
		method: 'POST',
		headers: headers,
		body: body
	}

	const response = await fetch('http://localhost:8080/contents', data)
	.then((response) => {return (response.json()).then((data) => {return data})}).catch((error) => {
		console.log(error)
	})
	return response
}

備考:NGだったパターン

2つ目bodyのセットの仕方によってはうまくいくかもしれない。
3つめのContent-Type削除はおそらく特殊ケース。

参考

どんぴしゃだったStackOverflowの質問

FormData#append (MDN)

2
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
2
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?