티스토리 뷰

Java

파일 다운로드

LichKing 2014. 12. 23. 10:21

InputStream in        = null;
        OutputStream out    = null;
        File file    = null;

        try{
            file    = new File(path, newName);
            in        = new BufferedInputStream(new FileInputStream(file));
            out     = new BufferedOutputStream(response.getOutputStream());
            oldName = URLEncoder.encode(oldName, "UTF-8").replaceAll("\\+", " ");

            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + oldName);

            byte[] b = new byte[(int)file.length()];
            int leng = 0;

            while((leng = in.read(b)) > 0){
                out.write(b, 0, leng);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                out.close();
                in.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }


업로드에 비해 비교적 쉽다.

하나 첨언할것은 .replace("\\+", " ") 이부분인데 파일명에 공백이 있을경우 그 공백을 +로 출력하기때문에 그 +를 다시 공백으로 바꿔주는 작업임.

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