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
I’m doing something similar, but using Angular and Spring.
This is an example of the code in Angular that sends a request:
the content of this.apiService.post is this:
And this is an example of the code in Spring that accepts and processes that request:
I hope it helps you.
In the "save" method of your controller, add
(value="boardFile")
to the "file" RequestParam just like below and try again.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:
to this:
Or, in Spring, change:
to either:
or:
And on this line, instead of sending saveData, send formData:
Change it to look like this:
Delete @RequestParam on this line in Spring:
So it looks like this:
This should make it work. It works for me when I copy your code and make these changes.