티스토리 뷰

추후에 보기 편하도록 지금 생각한 내용을 정리하고자 한다.


가정.



1. 프로젝트 내부에 파일을 업로드할 경우, 프로젝트가 업데이트되어 소스를 교체하면 파일이 유지되지 않을 위험이 있다. 따라서 빌드된 프로젝트의 리소스사용자가 업로드한 리소스(프로젝트와 동일 레벨의 upload디렉터리로 가정)는 따로 관리하는 것으로 가정한다. 


2. FileCopyUtils.copy(inputStream in, outputStream out)을 사용할 것이므로 파일을 inputStream으로 받는다.



다운로드



- 프로젝트에 기본으로 포함되는 리소스(ex. 양식) 들을 다운로드 하는 경우는 아래의 코드를 사용한다.

InputStream in = getClass().getClassLoader().getResourceAsStream("static/xxx");

- 프로젝트 외부에 사용자가 업로드한 리소스의 다운로드는 아래의 코드를 사용한다.

File userUploadDir = new File("upload");

if (!userUploadDir.exists()) {

    userUploadDir.mkdir();

}

File f = new File("upload/.gitignore");

InputStream in = new FileInputStream(f.getAbsolutePath());

IDE에서는 프로젝트 디렉터리 내부에 upload 디렉터리를 사용하고, 리눅스 환경에 jar 배포시에는 같은 레벨의upload 디렉터리를 사용


++ 추가.

1. 상기 코드 이후 바로 FileCopyUtils.copy(inputStream in, outputStream out)을 사용하면 파일 자체를 웹브라우저에서 읽어들인다. 다운로드를 위해선 HttpservletResponse 객체의 setHeader 메소드를 통해 해당 파일이 첨부 파일임을 명시해줘야 한다.

response.setHeader("Content-Disposition", "attachment; filename=" + fileName);


2. 기능상 문제는 없으나 다음의 익셉션이 뜬다. HTTP Status 500 - java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

public String upload(@RequestParam("file") MultipartFile file) throws IOException {

File userUploadDir = new File("upload");

if (!userUploadDir.exists()) {

    userUploadDir.mkdir();

}

String storePath = userUploadDir.getAbsolutePath() +"/"+ file.getOriginalFilename();

FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(storePath));


return "redirect:/";

위 코드에서 리턴 타입 때문으로 유추된다. HTTP 프로토콜은 하나의 요청에 대해 하나의 응답을 제공하고 커넥션을 끊는다. 따라서 위의 코드를 예로들면, 첨부파일을 반환할 때 이미 응답이 끝났는데 다시 redirect로 응답을 하려니, 커밋된 응답에 대해선 Redirect를 호출할 수 없다고 익셉션이 반환되는것으로 보인다.



업로드



- storePath 부분을 출력하면 "C:\Users\strai\Downloads\excel_upload\upload/save.name" 형식으로 나온다. 기능상 문제는 없으나, 거슬린다면 기존 userUploadDir.getAbsolutePath()을 StringUtils.cleanPath(userUploadDir.getAbsolutePath()) 으로 수정하면 "\"(역슬레시)를 "/"슬레시로 바꿔서 출력해준다.

File userUploadDir = new File("upload");

if (!userUploadDir.exists()) {

    userUploadDir.mkdir();

}

String storePath = userUploadDir.getAbsolutePath() +"/"+ file.getOriginalFilename();

FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(storePath));


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함