LoginSignup
2
3

More than 1 year has passed since last update.

REST ClientでファイルアップロードのAPIを投げる

Last updated at Posted at 2022-05-19

送信側

REST Clientで例としてtext, png, csv, wavの4つのファイルを送信する

test.http
POST https://api.example.com/user/upload
Content-Type: multipart/form-data; boundary=boundary

--boundary
Content-Disposition: form-data; name="text"; filename="sample.txt"
Content-Type: text/plain

text contents
--boundary
Content-Disposition: form-data; name="image"; filename="sample.png"
Content-Type: image/png

< ./sample.png
--boundary
Content-Disposition: form-data; name="csv"; filename="sample.csv"
Content-Type: text/csv

< ./sample.csv
--boundary
Content-Disposition: form-data; name="wav"; filename="sample.wav"
Content-Type: audio/wav

< ./sample.wav
--boundary--

ポイント

  • リクエストのContent-Typeをmultipart/form-dataにする
  • boundary(境界線)の名前は任意で決められる
  • 各ファイルごとに--(境界線名)で区切る
  • ファイルの終了は--(境界線名)--
  • 各ファイルのnameは受け取る時の配列キーになる
  • 各ファイルのContent-TypeはアップロードしたいMIMEタイプを指定する
  • 各ヘッダとデータの間は一行空ける
  • <は入力ストリームでデータへのファイルパスを指定する(テキストの場合はデータをベタ書きでもOK)

受け取り側(Laravelの場合)

コントローラ

class UpdateController extends DefaultController
{
    public function uploadSample(Request $request): JsonResponse
        $files = $request->file();

        $text_file = $files['text'];
        $image_file = $files['image'];
        $csv_file = $files['csv'];
        $wav_file = $files['wav'];
}

ルーティング

Route::post('/user/upload', [UpdateController::class, 'uploadSample']);

参考

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