Learn how to create a Java 8 REST API controller that accepts a CSV file as a multipart

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.

***************************************************
Thanks for being here.

Happy Coding ✌💕💖

***************************************************

  • Are you an android developer and carrying a USB cable to test, debug, and run your app? this article is for you. World's 1st and only ...
  • Here in this post, we'll see how to connect or call a localhost endpoint or API when we are developing a real android application. but b...
  •  Clear or evict all cache Programmatically. Does Java provide something which can clear all the cache at once?👆👆👆👆❓❓❓ The answer is NO ...
  • Here is the shortest way to swap two numbers in java.   we can swap two numbers just by using a single line of code. First of all, let me cl...
  • No comments:

    Post a Comment