반응형
05-14 05:47
Today
Total
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
관리 메뉴

개발하는 고라니

[Spring] 파일 업로드 본문

Framework/Spring

[Spring] 파일 업로드

조용한고라니 2021. 2. 25. 00:39
반응형

1. MultipartFile의 transferTo()

2. FileCopyUtils 이용

 

파일을 업로드하는 방법은 크게 2가지가 있다. 하나는 HTML의 form태그를 이용하는 것이고, 하나는 ajax를 이용하는 방법이 있다.

업로드한 파일을 로컬 저장소에 저장하는 방법을 알아보고자 한다.

# 파일 업로드

Ajax를 이용해 Spring에서 지원하는 Multipart 타입으로 파일을 받는다.

 

1. C:\upload\temp : 파일 저장 경로

2. 저장될 파일 명 : UUID_filename.png (UUID는 파일의 고유 번호로, 파일명 중복 방지를 위해 적용한다.)

 

# 1. Multipart의 transferTo(Path path) 이용하기

    @PostMapping(value = "/upload")
    public void uploadFile(MultipartFile[] uploadFiles){

        for(MultipartFile file : uploadFiles){

            String originalName = file.getOriginalFilename();
            String fileName = originalName.substring(originalName.lastIndexOf("\\") + 1);

            String uuid = UUID.randomUUID().toString();

            String savefileName = uploadPath + File.separator + uuid + "_" + fileName;

            Path savePath = Paths.get(savefileName);

            try {
                file.transferTo(savePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

# 2. FileCopyUtils의 copy() 이용하기

    @PostMapping(value = "/upload")
    public void uploadFile(MultipartFile[] uploadFiles){

        for(MultipartFile file : uploadFiles){

            String originalName = file.getOriginalFilename();
            String fileName = originalName.substring(originalName.lastIndexOf("\\") + 1);


            String uuid = UUID.randomUUID().toString();

            String savefileName = uploadPath + File.separator + uuid + "_" + fileName;

            Path savePath = Paths.get(savefileName);

            try {
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(savePath.toFile()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

※ FileCopyUtils

void copy(byte[] in, File out)

byte[]를 지정한 File에 복사
void copy(byte[] in, OutputStream out)

byte[]를 지정한 OutputStream에 복사하고, stream을 닫는다
int copy(File in, File out)

out파일을 in파일로 복사하고, 복사한 byte수 return
int copy(InputStream in, OutputStream out)

in의 내용을 out에 복사하고 스트림 닫는다. byte수 return
int copy(Reader in, Writer out)

Reader의 내용을 Writer에 복사하고 copy된 문자 수 return
void copy(String in, Writer out)

String의 내용들을 Writer에 복사한다
byte[] copyToByteArray(InputStream in)

InputStream의 내용을 byte[]에 담아 보낸다.
byte[] copyToByteArray(File in)

File의 내용을 byte[]에 담아 보낸다.

 

# References

니 자신 있나?님의 블로그

반응형
Comments