카테고리 없음

[ Spring-Boot ] 파일 업로드 사용하기

사과씨앗 2021. 5. 22. 16:49
반응형

안녕하세요 이번 글에서는 파일 업로드하는 방법을 정리하여 보겠습니다.

 

간단하게 아래처럼 화면을 구성하겠습니다.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form action="/file/save" enctype="multipart/form-data" method="post">
        <input type="file" name="uploadFile" >

        <button type="submit">파일업로드</button>
    </form>
</body>
</html>

 

@RestController
@RequestMapping("/file")
public class FileController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UploadFileService fileService;

    /**
     * 업로드 리턴
     */
    @PostMapping("/save")
    @ApiOperation(value="업로드",notes = "")
    public BaseResponse<Boolean>save(@RequestParam("uploadFile") MultipartFile multipartFile){

        String getUploadFilePath = "C:/home/upload/"; //파일이 저장될 경로를 설정
        String getUploadResourcePath = "/upload/";
        //파라미터로 넘어온 파일이 없을때 예외처리
        if(multipartFile == null || multipartFile.isEmpty()){
            throw new BaseException(BaseResponseCode.DATA_IS_NULL);
        }
        //날짜폴더 추가
        String currentDate = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
        String uploadFilePath = getUploadFilePath+ currentDate + "/";
        //업로드 할 원본 파일의 확장자 가져오기
        String prefix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") +1, multipartFile.getOriginalFilename().length());
        //파일이름을 생성한 뒤 확장자 설정
        String filename = UUID.randomUUID().toString()+"."+ prefix;
        //파일을 포함한 경로 설정
        String pathname = uploadFilePath + filename;
        String resourcePathname = getUploadResourcePath + currentDate + "/" + filename;

        //오늘 잘짜의 폴더가 없을 경우 생성하여 주기
        File folder = new File(uploadFilePath);
        if(!folder.isDirectory()){
            folder.mkdirs();
        }

        File dest = new File(pathname);
        try {
            multipartFile.transferTo(dest);
            //파일업로드 된 후 DB에 저장
            UploadFileParameter parameter = new UploadFileParameter();
            //컨텐츠 종류
            parameter.setContentType(multipartFile.getContentType());
            //원본 파일명
            parameter.setOriginalFilename(multipartFile.getOriginalFilename());
            //저장 파일명
            parameter.setFilename(filename);
            //실제파일 저장경로
            parameter.setPathname(pathname);
            //파일크기
            parameter.setSize((int)multipartFile.getSize());
            // static resource 접근경로
            parameter.setResourcePathname(resourcePathname);

            fileService.save(parameter);
        } catch ( IllegalStateException | IOException e) {
            e.printStackTrace();
        }

        return new BaseResponse<Boolean>(true);
    }
}

DB에 저장하는 코드는 단순 insert 이기 때문에 생략하겠습니다.

 

감사합니다 ^^  

 

 

참고 영상 : https:/www.inflearn.com/course/backend-%EC%86%A1%EC%9E%90%EB%B0%94/dashboard

728x90
반응형