java multiple files upload example
Here's an example of uploading multiple files in Java using the Spring Framework:
- Add the following dependency in your Maven
pom.xmlfile:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>S:ecruowww.theitroad.com- Create a controller to handle the file upload:
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity<?> uploadFile(@RequestParam("files") List<MultipartFile> files) {
// Process the files here
// ...
return ResponseEntity.ok("Files uploaded successfully");
}
}
- Create a HTML form to allow users to select and upload multiple files:
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="files" multiple>
<button type="submit">Upload</button>
</form>
This form allows users to select multiple files using the multiple attribute of the <input> tag. When the form is submitted, the files are sent to the server using the multipart/form-data encoding.
- Run the Spring Boot application and navigate to
http://localhost:8080to test the file upload.
This example uses the Spring @RequestParam annotation to bind the uploaded files to a List<MultipartFile> parameter. You can process the files as needed, such as saving them to disk or processing them in memory.
