springboot のファイル アップロードには多くの実装スキームがありますが、個人的な比較では、エンティティ クラス属性のバインドによるスキーム 3 を推奨します。
オープンソースは pom に依存します
<!-- 基于springboot的请求AOP拦截、返回值包装、全局异常处理SDK -->
<dependency>
<groupId>io.github.mingyang66</groupId>
<artifactId>emily-spring-boot-starter</artifactId>
<version>4.3.5</version>
</dependency>
1. 単一ファイルのアップロードとその他の属性フィールド
@PostMapping(value = "/uploadSingle", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadSingle(@RequestParam("file") MultipartFile file, @RequestParam("file1") MultipartFile file1, @RequestParam("name") String name, @RequestParam("desc") String desc) throws IOException {
byte[] fileContent = file.getBytes();
byte[] fileContent1 = file1.getBytes();
// 处理上传的文件内容
return "File uploaded successfully!";
}
2. 複数のファイルを配列でアップロードする
@PostMapping(value = "/uploadArray", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String handleFileUpload(@RequestParam("files") MultipartFile[] files) throws IOException {
byte[] fileContent = files[0].getBytes();
// 处理上传的文件内容
return "File uploaded successfully!";
}
3. ファイルをアップロードし、エンティティ クラス バインディングを通じて他の属性値を渡す
@PostMapping(value = "/uploadMul", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadMul(@ModelAttribute("request") FileUploadRequest request) throws IOException {
byte[] fileContent = request.getFile().getBytes();
byte[] imageFileContent = request.getImageFile().getBytes();
String accountCode = request.getAccountCode();
String address = request.getAddress();
// 处理上传的文件内容
return "File uploaded successfully!";
}
4. エンティティクラスバインディングを通じて複数のファイルをアップロードする
@PostMapping(value = "/uploadMuls", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadMuls(@ModelAttribute FileUploadRequest[] request) throws IOException {
byte[] fileContent = request[0].getFile().getBytes();
byte[] imageFileContent = request[0].getImageFile().getBytes();
String accountCode = request[0].getAccountCode();
String address = request[0].getAddress();
// 处理上传的文件内容
return "File uploaded successfully!";
}
GitHub ソースコード: https://github.com/mingyang66/spring-parent