Here is an example of a Java 8 REST API controller that accepts a CSV file as a multipart request and prints the values of the studentName
and studentEmail columns:
****************************************************
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.stream.Collectors; 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 CSVController { @PostMapping("/process-csv") public void processCSV(@RequestParam("file") MultipartFile file) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream())); reader.lines().skip(1) // skip the header row .map(line -> line.split(",")) .forEach(columns -> System.out.println("studentName: " + columns[0] + ", studentEmail: " + columns[1])); } }
****************************************************
This controller has a single endpoint, /process-csv, which accepts a multipart request with a file parameter. The file is read using a BufferedReader, and the lines are processed using Java 8 streams. The first line (the header row) is skipped, and the remaining lines are split on the comma delimiter and mapped to an array of strings. Finally, the values of the studentName and studentEmail columns are printed to the console.
Note that this is just a simple example and you may want to add additional error handling and validation logic as needed for your specific use case.
No comments:
Post a Comment