성동스터디 (2021.09.09 ~ ing)/React + Spring
[Spring][React] 이미지 업로드
juniKang
2021. 12. 19. 15:27
1. 이미지 업로드 : https://junikang.tistory.com/289
2. 이미지 불러오기 : https://junikang.tistory.com/303
응용예시
프론트엔드
- 제목과 내용을 입력받는 post와
- 이미지를 첨부할 수 있는 file을 만들어서 각각 입력받습니다.
- 입력받은 데이터를 FormData에 append 해서
- 백엔드로 post요청을 보내겠습니다.
const Write = (props) => {
const [post, setPost] = useState();
const [file, setFile] = useState();
const changeValue = (e) => {
setPost({
...post,
[e.target.name]: e.target.value,
});
};
const saveFile = (e) => {
setFile(e.target.files[0]);
};
const submitPost = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('file', file);
formData.append('post', JSON.stringify(post));
fetch('http://loaclhsot:8080/post',{
method: 'POST',
body: formData,
})
.then(props.history.push('/'));
};
return (
<form onSubmit={submitPost}>
<input type="text" name="title" onChange={changeValue} />
<input type="text" name="contents" onChange={changeValue} />
<input type="file" onChange={saveFile} />
<button type="submit">등록</button>
</form>
);
};
export default Write;
백엔드
- formData 로 들어온 요청을 받아 file은 MutipartFile 타입에 매핑하고, post는 문자열로 매핑합니다.
- 매핑된 sringPost문자열을 Post객체로 변환합니다.
- 경로와 중복되지않는 파일 이름을 만들고,
- File.wrtie() 메소드로 지정한 경로에 file을 저장합니다.
- post 객체에 image를 입력하고 DB에 저장합니다.
@CrossOrigin
@PostMapping("/post")
public ResponseEntity<?> fileUpload(@RequestParam MultipartFile file,
@RequestParam("post") String stringPost) throws Exception {
//stringPost의 값 {title: "...", contents: "..."}을 Post.class 객체에 맵핑합니다.
Post post = new ObjectMapper().readValue(stringPost, Post.class);
String path = "C:\\juni\\repository\\image\\";
String imageFileName = Math.random() + "_" + file.getOriginalFilename();
Path imageFilePath = Paths.get(PATH + imageFileName);
Files.write(imageFilePath, file.getBytes());
post.setImage(imageFileName); // file이름을 post객체에 set 합니다.
return new ResponseEntity<>(postService.save(post), HttpStatus.CREATED);
}