Spring file download

북마크 추가

스프링 파일 다운로드

 

ex)

<a href="/file/download?fileNm=201603220736012343&originalFileNm=asdf.txt"/>download</a>

-> 서버상에 201603220736012343 라는 이름으로 변환되어 저장돼 있는 파일을 다운로드 하려고 할때 실제 파일이름 asdf.txt로 다운 받는 방법 

 * 파일명에 공백이 있는경우 URIEncoding하거나 변환된 파일명으로 쿼리돌려서 원본파일명을 가져와야 됨

 

@RequestMapping(value="/file/download", method = RequestMethod.GET)

    public void downloadFile(HttpServletResponse response,String fileNm, String originalFileNm) throws IOException {

 

        File file = new File("server file path");  // ex) /var/webapps/upload/201603220736012343                 

        if(!file.exists()){

            String errorMessage = "Sorry. The file you are looking for does not exist";

            System.out.println(errorMessage);

            OutputStream outputStream = response.getOutputStream();

            outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));

            outputStream.close();

            return;

        }

         

        String mimeType= URLConnection.guessContentTypeFromName(file.getName());

        if(mimeType==null){

            System.out.println("mimetype is not detectable, will take default");

            mimeType = "application/octet-stream";

        }

         

        System.out.println("mimetype : "+mimeType);

         

        response.setContentType(mimeType);

         

       

        response.setHeader("Content-Disposition", String.format("inline; filename=\"" + originalFileNm+"\"")); // 저장할때 사용될 실제 파일명 

         

        response.setContentLength((int)file.length());

 

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); 

    

        FileCopyUtils.copy(inputStream, response.getOutputStream());

    }

 

AD
관리자
2016-03-22 19:46
SHARE