LoginSignup
5
2

More than 1 year has passed since last update.

React axiosを使用して画像ファイルをAPI送信したい

Posted at

目的

Reactで画像などのファイルデータをAPIに送信する方法をまとめてみました。
以下の方に、参考になれば幸いです。
・Reactの画像ファイルの送り方がわからない。
・axiosを使用して送信したい。

今回は、画像ファイルと文字ファイルを同時に送っています。

導入

axiosライブラリを使用する準備をします。

ターミナル
npm install axios

画像ファイルの送信方法

以下のコードで送信することができた。

send,js
import React from 'react';
import { useState } from 'react';
import axios from 'axios';

function Send() {
 const [title,setTitle] = useState();
 const [image,setImage] = useState();

 const handleSubmit = () => {

   const file = new FormData()
   file.append("title",title);
   file.append("image", image[0]);

axios
      .post('http://localhost/api/sendimage',file,
        {
          headers: {
          'content-type': 'multipart/form-data',
          },
        }
      )
      .then(response => {
        console.log(response);
      })
 }

   return (
     <>
      <p>ファイル送信</p>
       <input type="text" placeholder="写真のタイトル"
onChange={event => setTitle(event.target.value)} />

      <input accept="image/*" multiple type="file"
onChange={event => setImage(event.target.files)} />
<button onClick={handleSubmit}>送信</button>
</>
);
}

export default Send;

解説

まずは、axiosライブラリをimportする。

send,js
import axios from 'axios';


画像ファイル、文字データ(写真タイトル)をuseStateに保管し、送信ボタンクリックでAPI通信が発火します。
ここでの注意点はonChangeでファイルを保管する際に、画像ファイルはevent.target.filesを使用し、
文字ファイルはevent.target.valueを使用する。

send.js
<input type="text" placeholder="写真のタイトル"
onChange={event => setTitle(event.target.value)} />
<input accept="image/*" multiple type="file"
onChange={event => setImage(event.target.files)} />
<button onClick={handleSubmit}>送信</button>


API通信のところとなります。

send.js

const handleSubmit = () => {

  const file = new FormData();
  file.append("title",title);
  file.append("image", image[0]);

axios
    .post('http://localhost/api/sendimage',file,
      {
         headers: {
          'content-type': 'multipart/form-data',
          },
       }
     )
    .then(response => {
        console.log(response);
     })
}


まず、FormDataを定義します。
FormDataに、先程useStateに保管した画像ファイル及び文字データを追加します。

send.js

const file = new FormData();
file.append(title,title);
file.append("image", image[0]);


axios.postでAPI送信します。
先程定義したFormData={inputでuseStateに保管した画像ファイル}を送ります。
その際に、headerとして 'content-type': 'multipart/form-data'を指定します。
'multipart/form-data'は文字、ファイルなどの複数の種類のデータを一度に送信できる形式です。

send.js
axios
  .post('http://localhost/api/sendimage',file,
    {
      headers: {
        'content-type': 'multipart/form-data',
      },
    }
  )

まとめ

今回は、Reactで画像ファイルをAPI送信する方法をまとめてみました。
Laravelで受け取る側も作っているので、今後まとめますね。

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