skip to Main Content

I want to pass the file and information to Spring as data from React. But I get Axios error 400. Is there any problem with the React and Spring codes? I have little experience with Spring, so I’m unsure if I made it right. How can I hand over files and information? Any advice or solution, please? The language may be strange because it is written by a translator.

react

  const saveData = {
    boardWriter: sessionStorage.getItem("memberID"),
    boardTitle: title,
    boardContents: contents,
    boardFile: file,
  }
const write = () => {
    const formData = new FormData();

formData.append("boardWriter", sessionStorage.getItem("memberID"));
    
formData.append("boardTitle", title);
    
formData.append("boardContents", contents);
    
formData.append("boardFile", file);

    axios
      .post("http://localhost:8080/api/board/write", saveData, {
        headers: {
          "Content-Type": "multipart/form-data",
        }
      })
      .then(res => res.data)
      .catch(err => console.log(err));}

spring

controller

@PostMapping("/write")
    public void save(@RequestParam BoardDTO boardDTO,
                     @RequestParam MultipartFile file) throws IOException {
        
String fileName = file.getOriginalFilename();
        
file.transferTo(new File(fileName));
        
boardDTO.setBoardFile(fileName);
        
boardService.save(boardDTO);
  
} 

repository

public int save(BoardDTO boardDTO) {
        
return sql.insert("Board.save", boardDTO);
    
}

service

public int save(BoardDTO boardDTO) {
        
return boardRepository.save(boardDTO);
    
}

mapper

<mapper namespace="Board">

    <insert id="save" parameterType="board">
        insert into board(boardWriter, boardTitle, boardContents, boardFile)
        values(#{boardWriter}, #{boardTitle}, #{boardContents}, boardFile=#{boardFile})
    </insert>

3

Answers


  1. I’m doing something similar, but using Angular and Spring.

    This is an example of the code in Angular that sends a request:

      runCase(runDetails?: RunDetails, dataDrivenFile?: File) {
        const formdata: FormData = new FormData();
        if (dataDrivenFile) {
          formdata.append('dataDrivenFile', dataDrivenFile);
        }
        if (runDetails) {
          formdata.append('runDetails', new Blob([JSON.stringify(runDetails)], {
            type: 'application/json'
          }));
        }
    
        const headers = new HttpHeaders({
          Accept: 'application/json'
        });
    
        return this.apiService.post(this.cloudConfigService.runCase(), formdata, headers);
      }
    

    the content of this.apiService.post is this:

      post(path: string, body: any, customHeaders?: HttpHeaders): Observable<any> {
        return this.request(path, body, RequestMethod.Post, customHeaders);
      }
    
      private request(path: string, body: any, method = RequestMethod.Post, customHeaders?: HttpHeaders): Observable<any> {
        const req = new HttpRequest(method, path, body, {
          headers: customHeaders || this.headers,
          reportProgress: true,
          withCredentials: true
        });
    
        return this.http.request(req).pipe(
          filter(response => response instanceof HttpResponse),
          map((response: HttpResponse<any>) => response.body)
        );
      }
    

    And this is an example of the code in Spring that accepts and processes that request:

    @PostMapping(value = APIConfig.RUN_CASE_URL)
    public ResponseEntity runCase(
            @RequestPart(value = "dataDrivenFile", required = false) MultipartFile dataDrivenFile,
            @RequestPart("runDetails") RunDetails runDetails
    ) throws InterruptedException, IOException {
        runDetails.setDataDrivenFile(dataDrivenFile);
    
        runService.run(runDetails);
        
        return ResponseEntity.ok().build();
    }
    

    I hope it helps you.

    Login or Signup to reply.
  2. In the "save" method of your controller, add (value="boardFile") to the "file" RequestParam just like below and try again.

    @PostMapping("/write")
        public void save(@RequestParam BoardDTO boardDTO,
                         @RequestParam(value="boardFile") MultipartFile file) throws IOException {
    ...
    }
    
    Login or Signup to reply.
  3. You can do it in the way I showed in the previous answer you can find more details on how to do it here, or if you prefer, you can follow your initial approach with a few small modifications:

    Change this:

    formData.append("boardFile", file);
    

    to this:

    formData.append("file", file);
    

    Or, in Spring, change:

    @RequestParam MultipartFile file
    

    to either:

    @RequestParam MultipartFile boardFile
    

    or:

    @RequestParam(value="boardFile") MultipartFile file
    

    And on this line, instead of sending saveData, send formData:

     axios
          .post("http://localhost:8080/api/board/write", saveData, { 
    

    Change it to look like this:

     axios
          .post("http://localhost:8080/api/board/write", formData, {
    

    Delete @RequestParam on this line in Spring:

    public void save(@RequestParam BoardDTO boardDTO,
    

    So it looks like this:

    public void save(BoardDTO boardDTO,
    

    This should make it work. It works for me when I copy your code and make these changes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search