Skip to content

Commit

Permalink
fix: 이미지 업로드 위치 변경
Browse files Browse the repository at this point in the history
로컬 -> aws s3
  • Loading branch information
fernandokkang committed Apr 9, 2024
1 parent f5e6b2f commit a203dfc
Show file tree
Hide file tree
Showing 6 changed files with 128 additions and 11 deletions.
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'

implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
}

tasks.named('test') {
Expand Down
34 changes: 34 additions & 0 deletions src/main/java/com/estsoft/springproject/config/S3Config.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.estsoft.springproject.config;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class S3Config {

@Value("${cloud.aws.credentials.access-key}")
private String accessKey;

@Value("${cloud.aws.credentials.secret-key}")
private String secretKey;

@Value("${cloud.aws.region.static}")
private String region;

@Bean
public AmazonS3Client amazonS3Client() {

BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

return (AmazonS3Client) AmazonS3ClientBuilder
.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.estsoft.springproject.controller;

import com.estsoft.springproject.service.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
Expand All @@ -15,18 +17,34 @@

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/tui-editor")
public class FileApiController {

// 파일을 업로드할 디렉터리 경로
private final FileService fileService;

@PostMapping("/image-upload")
public String fileWrite(@RequestParam MultipartFile image) throws IOException {

return fileService.fileWrite(image);
}

@GetMapping("/image-print")
public byte[] printEditorImage(@RequestParam String filename) throws FileNotFoundException {

return fileService.fileLoad(filename);

}

/*// 파일을 업로드할 디렉터리 경로
private final String uploadDir = Paths.get(System.getProperty("user.dir"), "build", "resources", "main", "static", "images", "upload").toString();
/**
*//**
* 에디터 이미지 업로드
*
* @param image 파일 객체
* @return 업로드된 파일명
*/
*//*
@PostMapping("/image-upload")
public String uploadEditorImage(@RequestParam final MultipartFile image) throws FileNotFoundException {
if (image.isEmpty()) {
Expand Down Expand Up @@ -57,12 +75,12 @@ public String uploadEditorImage(@RequestParam final MultipartFile image) throws
}
}
/**
*//**
* 디스크에 업로드된 파일을 byte[]로 반환
*
* @param filename 디스크에 업로드된 파일명
* @return image byte array
*/
*//*
@GetMapping(value = "/image-print", produces = {MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
public byte[] printEditorImage(@RequestParam final String filename) {
// 업로드된 파일의 전체 경로
Expand All @@ -83,5 +101,5 @@ public byte[] printEditorImage(@RequestParam final String filename) {
// 예외 처리는 따로 해주는 게 좋습니다.
throw new RuntimeException(e);
}
}
}*/
}
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public String updateMypageInfo(@PathVariable Long userId,@ModelAttribute UserReq

userService.updateUserInfo(userId,userRequest);
model.addAttribute("user",user);
return "redirect:mypage";
return "redirect:/mypage";
}

@DeleteMapping("/mypage/{userId}")
Expand Down Expand Up @@ -172,7 +172,7 @@ public String getAllUsers(Model model,@AuthenticationPrincipal UserDetails userD
@PostMapping("/mypage/{userId}/admin")
public String updateRole(@PathVariable Long userId,@RequestParam String role){
userService.updateRole(userId,role);
return "redirect:mypage/admin";
return "redirect:/mypage/admin";
}

// spring security 관련 코드
Expand All @@ -183,11 +183,11 @@ public String updateRole(@PathVariable Long userId,@RequestParam String role){
//return "redirect:/login";
//}
//로그아웃 컨트롤러
@GetMapping("/logout")
/*@GetMapping("/logout")
public String logout(HttpServletRequest request, HttpServletResponse response){
new SecurityContextLogoutHandler().logout(request,response, SecurityContextHolder.getContext().getAuthentication());
return "redirect:login";
}
}*/

@PostMapping("/checkCurrentPassword")
public ResponseEntity<?> checkCurrentPassword(@RequestParam String currentPassword) {
Expand Down
62 changes: 62 additions & 0 deletions src/main/java/com/estsoft/springproject/service/FileService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.estsoft.springproject.service;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.util.IOUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class FileService {

private final AmazonS3 amazonS3;
@Value("${cloud.aws.s3.bucket}")
private String bucket;

public String fileWrite(MultipartFile file) throws IOException {

UUID uuid = UUID.randomUUID();

String directory = "images/base-loaded/";

String fileName = directory + uuid + "_" + file.getOriginalFilename();

ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(file.getSize());
metadata.setContentType(file.getContentType());

amazonS3.putObject(bucket, fileName, file.getInputStream(), metadata);

return fileName;
}

public byte[] fileLoad(String fileName) throws FileNotFoundException {

if(isNotExist(fileName)) {
throw new FileNotFoundException();
}

S3Object s3Object = amazonS3.getObject(bucket, fileName);
S3ObjectInputStream s3ObjectInputStream = s3Object.getObjectContent();

try {
return IOUtils.toByteArray(s3ObjectInputStream);
}catch (IOException e){
throw new FileNotFoundException();
}
}

private boolean isNotExist(String fileName) {

return !amazonS3.doesObjectExist(bucket, fileName);
}
}
3 changes: 2 additions & 1 deletion src/main/resources/static/js/boardEditor.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@ const editor = new toastui.Editor({
const formData = new FormData();
formData.append('image', blob);

console.log(formData);

const response = await fetch('/tui-editor/image-upload', {
method: 'POST',
body: formData,
});

const filename = await response.text();
console.log('서버에 저장된 파일명 : ', filename);

const imageUrl = `/tui-editor/image-print?filename=${filename}`;
callback(imageUrl, 'image alt attribute');
Expand Down

0 comments on commit a203dfc

Please sign in to comment.