read data from MultipartFile which has csv uploaded from browser

前端 未结 3 1842
无人及你
无人及你 2020-12-30 02:46

May be I am doing it worng by using MultipartFile upload feature.

I have to read data from csv file which will be chosen by the client through the browser. I used Mu

相关标签:
3条回答
  • 2020-12-30 03:04

    I used a buffer to read line by line and get from multipart the inputstream. Maybe is more code, but I find helpful read text file by lines.

    BufferedReader br;
    List<String> result = new ArrayList<>();
    try {
    
         String line;
         InputStream is = multipart.getInputStream();
         br = new BufferedReader(new InputStreamReader(is));
         while ((line = br.readLine()) != null) {
              result.add(line);
         }
    
      } catch (IOException e) {
        System.err.println(e.getMessage());       
      }
    
    0 讨论(0)
  • 2020-12-30 03:07

    The best solution that I found was

    @PostMapping(value="/csv")
    public ResponseEntity<Void> processUpload(@RequestParam MultipartFile file) {
    
    BufferedReader fileReader = new BufferedReader(new 
    InputStreamReader(file.getInputStream(), "UTF-8"));
    CSVParser csvParser = new CSVParser(fileReader, CSVFormat.DEFAULT);
    
    Iterable<CSVRecord> csvRecords = csvParser.getRecords();
    
    for (CSVRecord csvRecord : csvRecords) {
        System.out.println(csvRecord);
    }
    ...
    

    This is an adaptative solution from https://bezkoder.com/spring-boot-upload-csv-file/

    0 讨论(0)
  • 2020-12-30 03:10

    I figured out a workaround. I converted the file to bytes and then converted the bytes to String. From String I applied string.split() to get what I wanted out of the file.

        @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String uploadFileHandler(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                String completeData = new String(bytes);
                String[] rows = completeData.split("#");
                String[] columns = rows[0].split(",");
    
    0 讨论(0)
提交回复
热议问题