Skip to content

Instantly share code, notes, and snippets.

@kazuhito-m
Last active January 25, 2024 11:19
Show Gist options
  • Save kazuhito-m/c8018d8888aef192dfd867aa124aad5a to your computer and use it in GitHub Desktop.
Save kazuhito-m/c8018d8888aef192dfd867aa124aad5a to your computer and use it in GitHub Desktop.
org.springframework.web.multipart.MultipartFile の getInputStream() メソッドは何回呼んでも読み出せる、という例。
package com.kazuhitom.demo.presentation.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
@RestController
@RequestMapping("/upload")
public class ReadMultipartFileMultipleTimesController {
private static final Logger LOGGER = LoggerFactory.getLogger(ReadMultipartFileMultipleTimesController.class);
@PostMapping
@ResponseStatus(HttpStatus.OK)
public void uploadMultipartFile(@RequestParam("file") MultipartFile multipartFile) throws IOException {
for (int i = 1; i <= 5; i++) {
try (InputStream stream = multipartFile.getInputStream()) {
var fileText = new String(stream.readAllBytes());
LOGGER.info("アップロードされたテキスト呼び出し {}回目 : {}", i, fileText);
}
}
}
}
#!/usr/bin/env bash
# テスト用ファイル作成。
echo 'file for test. 日本語も混ぜておこうか。' > ./test_file.txt
# アップロード
curl -X POST http://localhost:8080/upload\
-F "file=@./test_file.txt;type=text/plain"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment