我想将文件和信息从React传递到Spring(@RequestParam或@RequestPart)

5hcedyr0  于 2023-03-22  发布在  Spring
关注(0)|答案(2)|浏览(168)

Spring says no data found in @RequestParam我试着改变@RequestPart或value,但不起作用。我怎么才能建立连接?谢谢你的任何建议,解决方案

React

boardWriter: sessionStorage.getItem("memberID"),
boardTitle: title,
boardContents: contents,
boardFile: file,
}
formData.append("saveData", new Blob([saveData]), {
type: "application/json",
})  
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));
}

控制器

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

仓库

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

服务

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

**error**
400 http bad request
Required BoardDTO parameter 'boardDTO' is not present
ilmyapht

ilmyapht1#

你可以使用@RequestParam和@ModelAttribute注解来实现文件的DTO。还有一些其他的代码,因为我重复使用了我写之前的代码。重点是如何在API端点获取数据。
下面是我的例子。

React
const formData = new FormData();
    const data = {
      boardWriter: "this is writer",
      boardTitle: 'this is title',
      boardContents: 'this is boardContents'
    }
    formData.append('boardFile', this.files[0]);
    formData.append('saveData', JSON.stringify(data))
    axios.post('http://localhost:8081/dto',
        formData,
        {headers: {'Content-Type': 'multipart/form-data'}})
Spring
@PostMapping(value = "/dto")
    public @ResponseBody
    String uploadFileInDto(@RequestParam("saveData") String saveData,
                           @RequestParam("boardFile") MultipartFile file) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        BoardDTO boardDTO = objectMapper.readValue(saveData, BoardDTO.class);
        System.out.println(saveData);
        System.out.println(boardDTO);
        System.out.println(file);
        return "upload success";
    }

更好的方式

我认为这是管理后端代码的更好方法。

React
const formData = new FormData();
    const data = {
      boardWriter: "this is writer",
      boardTitle: 'this is title',
      boardContents: 'this is boardContents'
    }
    for (let key in data) {
      formData.append(key, data[key])
    }
    formData.append('boardFile', this.files[0]);
    axios.post('http://localhost:8081/dto-2',
        formData,
        {headers: {'Content-Type': 'multipart/form-data'}})
Spring
@PostMapping(value = "/dto-2")
    public @ResponseBody
    String uploadFileInDto(@ModelAttribute BoardDTO boardDTO,
                           @RequestParam("boardFile") MultipartFile file) {
        System.out.println(boardDTO);
        System.out.println(file);
        return "upload success";
    }

你需要为DTO设置方法。

package blog.in.action.dto;

import lombok.*;

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Getter
@Setter
public class BoardDTO {

    private String boardWriter;
    private String boardTitle;
    private String boardContents;
}
qybjjes1

qybjjes12#

更改此内容:

formData.append("saveData", new Blob([saveData]), {
type: "application/json",
})

改为:

formData.append("saveData", new Blob([JSON.stringify(saveData)], {
        type: "application/json"
    }));

另外,您在下面的代码中似乎错误地发送了saveData,而不是formData

axios
  .post("http://localhost:8080/api/board/write", saveData, {
    headers: {
      "Content-Type": "multipart/form-data",
    }
  })

请将其更改为:

axios
      .post("http://localhost:8080/api/board/write", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        }
      })

这应该能让一切正常

相关问题