[내멋대로 만드는 Kimstagram] 8. 프로필 수정
이번에 할 것은 프로필을 수정하는 것이다.
예를 들면 프로필 사진이나 한 줄 커멘트 같은 거...
그런데 사실 프로필이라고 해봤자 수정할 게 저 둘 밖에 없어서... 그냥 어렵지 않게 구현했다.
프로필에서 '프로필 편집' 버튼을 누르면 위와 같은 프로필 편집 폼으로 이동한다.
실제 인스타그램에는 성별도 있고 웹사이트 주소도 넣을 수 있는데... 이건 딱히 구현해봤자 큰 의미는 없을 것 같아서 다 생략한다.
사진 변경은 게시물 업로드 때와 동일하게 MultipartFile으로 구현했다.
여기서 헤맸던 부분은... static 폴더에 image를 저장하면 서버를 재시작하기 전 까지는 서버에서 파일을 인식하지 못한다.
곰곰이 생각해 보면 당연한 게... static은 정적 리소스를 관리하는 폴더이므로 동적으로 리소스를 업로드하지 못하는 것!
그래서 업로드 경로를 webapp 하위 폴더로 변경하고, WebMvcConfigurer을 상속받은 WebMvcConfiguration을 만들어 addResourceHandlers()를 오버라이딩해서 동적 이미지를 관리하는 폴더의 경로를 따로 지정해 주었다.
package com.kimdev.kimstagram.Security;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/dynamicImage/**")
.addResourceLocations("file:./src/main/webapp/image/");
}
}
이제 이미지 요청이 "/dynamicImage/" 하위로 들어오면, 그 요청은 /webapp/image/ 하위에서 처리된다.
즉 static 하위 폴더에 이미지를 업로드하는 것이 아니므로, 동적으로 리소스가 즉각즉각 반영된다는 것!!
여튼 저렇게 프로필 사진을 업로드하고 한 줄 커멘트도 입력해서 제출 버튼을 누르면 아래의 profile_save() 함수가 호출된다.
function profile_save() {
$.ajax({
type: "GET",
url: "/getPrincipal",
headers: {'Authorization':localStorage.getItem('Authorization')},
contentType: "application/json; charset=utf-8",
}).done(function(resp) {
let data = new FormData();
data.append('accountId', principal.id);
data.append('comment', document.getElementById('commentInput').value);
data.append('picture', oriImages, 'profile');
principal = resp;
$.ajax({
type: "PUT",
url: "/profile/editProfile",
data: data,
contentType: false,
processData: false
}).done(function (resp){
alert("편집이 완료되었습니다.");
location.href = "/profile/" + principal.username;
}).fail(function(error){
alert(JSON.stringify(error));
});
});
}
@PutMapping("/profile/editProfile")
public int editProfile(@RequestParam("accountId") int accountId,
@RequestParam("comment") String comment,
@RequestPart("picture") MultipartFile picture) throws IOException {
int result = profileService.editProfile(accountId, comment, picture);
return result;
}
@Transactional
public int editProfile(int accountId, String comment, MultipartFile picture) throws IOException {
Account principal = accountRepository.findById(accountId).get();
principal.setComment(comment);
principal.setUse_profile_img(1);
// 프로필 이미지 저장
File path = new File("C:/Users/김현욱/Desktop/Java/kimstagram/src/main/webapp/image/profile/" + principal.getUsername() + "/");
if (!path.exists()) {
path.mkdirs();
}
File file = new File(path, "profile.jpg");
picture.transferTo(file);
return 1;
}
그러면 이제 프로필 수정이 완료된다.
[Spring] 간단한 이미지 업로드 및 정적 리소스를 통한 이미지 조회를 구현해보자.
필자가 진행하는 토이 프로젝트 냥피스에서는 이미지를 업로드 하는 기능과 이미지 조회 기능을 제공한다. 해당 기능을 구현하기 위해서 도움이 될만한 내용이 있으므로 이 기능을 구현하기 위
hoon9901.github.io