title: Upload CSV file from React and Spring Boot
body: <p>Maybe anybody knows how to solve the problem of uploading files to the back-end.
  <a href="https://i.stack.imgur.com/0egbB.jpg" rel="nofollow noreferrer">Send file from Postman looks like</a>
  But after upload from React, I have exception like this:</p>
  <blockquote>
  <p>2020-11-09 18:17:38.829 DEBUG 10764 --- [nio-8081-exec-7] o.s.web.servlet.DispatcherServlet : POST &quot;/api/employees/save-from-csv&quot;, parameters={masked} 2020-11-09 18:17:38.829 DEBUG 10764 --- [nio-8081-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.bank.controller.EmployeeController#uploadFile(MultipartFile, Model) 2020-11-09 18:17:38.831 DEBUG 10764 --- [nio-8081-exec-7] .w.s.m.m.a.ServletInvocableHandlerMethod : Could not resolve parameter [0] in public org.springframework.http.ResponseEntity&lt;com.bank.message.ResponseMessage&gt; com.bank.controller.EmployeeController.uploadFile(org.springframework.web.multipart.MultipartFile,org.springframework.ui.Model) throws java.io.IOException: Required request part 'file' is not present 2020-11-09 18:17:38.831 DEBUG 10764 --- [nio-8081-exec-7] .m.m.a.ExceptionHandlerExceptionResolver : Using @ExceptionHandler com.bank.exceptions.FileUploadExceptionAdvice#handleException(Exception, WebRequest) 2020-11-09 18:17:38.832 DEBUG 10764 --- [nio-8081-exec-7] o.s.w.s.m.m.a.HttpEntityMethodProcessor : No match for [application/json, text/plain, /], supported: [] 2020-11-09 18:17:38.833 WARN 10764 --- [nio-8081-exec-7] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present] 2020-11-09 18:17:38.837 DEBUG 10764 --- [nio-8081-exec-7] o.s.web.servlet.DispatcherServlet : Completed 400 BAD_REQUEST</p>
  </blockquote>
  <p><strong>This code for sending a file from React form :</strong></p>
  <pre><code>class UploadFiles extends Component{
  
  state = {
      file : ''
  };
  
  componentDidMount = () =&gt; {
      const {file} = this.props;
      this.setState({ file })
  };
  
  uploadFile = ({target : {files}}) =&gt; {
      console.log(files[0]);
      let data = new FormData();
      data.append('file', files);
  
  
      axios.post(&quot;/api/employees/save-from-csv&quot;, data)
          .then(res =&gt; {console.log(res)})
  };
  
  render(){
      return(
          &lt;div className=&quot;container&quot;&gt;
              &lt;div className=&quot;row&quot;&gt;
                  &lt;div className=&quot;col-md-6&quot;&gt;
                      &lt;div className=&quot;form-group files color&quot;&gt;
                          &lt;label&gt;Upload Your File &lt;/label&gt;
                          &lt;input type=&quot;file&quot; onChange={this.uploadFile}/&gt;
                      &lt;/div&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      )
  }}
  </code></pre>
  <p><strong>Service</strong></p>
  <pre><code>public void csvToEmployees(@RequestParam(&quot;file&quot;) MultipartFile file, Model model) {
      // validate file
      if (file.isEmpty()) {
          model.addAttribute(&quot;message&quot;, &quot;Please select a CSV file to upload.&quot;);
          model.addAttribute(&quot;status&quot;, false);
      } else {
  
          try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
  
              CsvToBean csvToBean = new CsvToBeanBuilder(reader)
                      .withType(Employee.class)
                      .withIgnoreLeadingWhiteSpace(true)
                      .build();
  
              List users = csvToBean.parse();
              employeeRepository.saveAll(users);
  
              model.addAttribute(&quot;users&quot;, users);
              model.addAttribute(&quot;status&quot;, true);
  
          } catch (Exception ex) {
              model.addAttribute(&quot;message&quot;, &quot;An error occurred while processing the CSV file.&quot;);
              model.addAttribute(&quot;status&quot;, false);
          }
      }
  
  }
  </code></pre>
  <p><strong>Controller</strong></p>
  <pre><code> @PostMapping(&quot;/employees/save-from-csv&quot;)
  public ResponseEntity&lt;ResponseMessage&gt; uploadFile(@RequestParam(&quot;file&quot;) MultipartFile file, Model model) throws IOException {
      ResponseEntity&lt;ResponseMessage&gt; result = null;
      boolean finished = false;
      String message = &quot;&quot;;
  
      if (CSVHelper.hasCSVFormat(file)) {
          try {
              service.csvToEmployees(file, model);
              message = &quot;Uploaded the file successfully: &quot; + file.getOriginalFilename();
              result = ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
              finished = true;
          } catch (Exception e) {
              message = &quot;Could not upload the file: &quot; + file.getOriginalFilename() + &quot;!&quot;;
              message += e;
              result = ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(new ResponseMessage(message));
              finished = true;
          }
      }
      if (!CSVHelper.hasCSVFormat(file)){
  
          message = &quot;File is empty!&quot;;
          result = ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseMessage(message));
      }
      if (!finished) {
          message = &quot;Please upload a csv file!&quot;;
          result = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage(message));
      }
      return result;
  }
  </code></pre>
  <p><strong>CSVHelper</strong></p>
  <pre><code>public class CSVHelper {
  
      public static boolean hasCSVFormat(MultipartFile file) {
  
          String TYPE = &quot;text/csv&quot;;
          return TYPE.equals(file.getContentType());
      }
  
      public static List&lt;Employee&gt; csvToEmployees(InputStream is) {
          try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(is, &quot;UTF-8&quot;));
               CSVParser csvParser = new CSVParser(fileReader,
                       CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());) {
  
              List&lt;Employee&gt; employees = new ArrayList&lt;&gt;();
  
              Iterable&lt;CSVRecord&gt; csvRecords = csvParser.getRecords();
  
              for (CSVRecord csvRecord : csvRecords) {
                  Employee employee = new Employee(
                          Long.parseLong(csvRecord.get(&quot;Id&quot;)),
                          csvRecord.get(&quot;Name&quot;),
                          Long.parseLong(csvRecord.get(&quot;DepartmentId&quot;)),
                          Double.parseDouble(csvRecord.get(&quot;Salary&quot;)),
                          csvRecord.get(&quot;City&quot;),
                          csvRecord.get(&quot;Street&quot;),
                          csvRecord.get(&quot;BankName&quot;),
                          csvRecord.get(&quot;CardNumber&quot;)
                  );
  
                  employees.add(employee);
              }
  
              return employees;
          } catch (IOException e) {
              throw new RuntimeException(&quot;fail to parse CSV file: &quot; + e.getMessage());
          }
      }
  
  }
  </code></pre>
  <p><strong>UnitTest</strong></p>
  <pre><code>@Test
      public void saveEmployeesFromCSV() throws Exception {
          String url = &quot;/api/employees/save-from-csv&quot;;
  
  
          String csvBuilder = &quot;name,departmentId,salary,city,street,bankName,cardNumber\n&quot; +
                  &quot;Maxim,1,3855,Madrid,Street,Bank York,NY98675432100\n&quot;;
          InputStream is = new ByteArrayInputStream(csvBuilder.getBytes());
  
          MockMultipartFile mockFile = new MockMultipartFile(&quot;file&quot;, &quot;employees.csv&quot;, &quot;text/csv&quot;, is);
  
          MockHttpServletResponse responseMessage = mvc.perform(MockMvcRequestBuilders.multipart(url)
                  .file(mockFile)
                  .param(&quot;file&quot;, &quot;employees2.csv&quot;))
                  .andReturn()
                  .getResponse();
          assertEquals(responseMessage.getStatus(), 200);
      }
  </code></pre>