2012-08-01 3 views
0

사용자가 .log 파일을 다운로드 할 수있는 페이지를 만들려고합니다. 이 코드는 다음과 같습니다.봄에서 모델 및 뷰에서 파일 다운로드

if(action.equalsIgnoreCase("download")){ 
     String file = (String)request.getParameter("file"); 
     response.setHeader("Content-Disposition", 
     "attachment;filename="+file+""); 
     response.setContentType("text/plain"); 

     File down_file = new File("log/"+file); 

     FileInputStream fileIn = new FileInputStream(down_file); 
     ServletOutputStream out = response.getOutputStream(); 

     byte[] outputByte = new byte[4096]; 
     //copy binary contect to output stream 
     while(fileIn.read(outputByte, 0, 4096) != -1) 
     { 
     out.write(outputByte, 0, 4096); 
     } 
     fileIn.close(); 
     out.flush(); 
     out.close(); 

     return null; 
} 

어디에서 잘못 했습니까?

IOUtils.copy(fileIn, response.getOutputStream()); 
response.flushBuffer(); 

아파치 커먼즈 IO를 여기에서 찾을 수 있습니다 내가 다운로드 버튼을 클릭하면 로 시도 ...

+1

'down_file.canRead()'가 true를 반환합니까? – Xaerxess

+0

예, true를 반환합니다. – Medioman92

답변

5

이 작업을 수행해야합니다

ByteStreams.copy 멋진 Google's Guava library에서 오는
public void getFile(final HttpServletResponse response) { 
    String file = (String) request.getParameter("file"); 
    response.setHeader("Content-Disposition", 
        "attachment;filename=" + file); 
    response.setContentType("text/plain"); 

    File down_file = new File("log/" + file); 
    FileInputStream fileIn = new FileInputStream(down_file); 
    ByteStreams.copy(fileIn, response.getOutputStream()); 
    response.flushBuffer(); 

    return null; 
} 

.

편집 : 당신은 당신이 청소기 방법으로 그것을 할 수있는 스프링 MVC 3.1를 사용하는 경우 또한

(즉, 내가 할 방법은 한 줄 것으로 판명)) :

@Controller 
public final class TestController extends BaseController { 

    @RequestMapping(value = "/some/url/for/downloading/files/{file}", 
        produces = "text/plain") 
    @ResponseBody 
    public byte[] getFile(@PathVariable final String file) throws IOException { 
     return Files.toByteArray(new File("log/" + file)); 
    } 

} 

하고 servlet.xml 추가 컨버터 mvc:message-converters에 그래서

<mvc:annotation-driven> 
    <mvc:message-converters> 
     <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" /> 
    </mvc:message-converters> 
</mvc:annotation-driven> 

당신이에서 byte[]를 반환 할 수 임의의 @Controller 메서드는 @ResponseBody으로 주석 처리됩니다. 더 읽기 herehere.

Files.toByteArray도 구아바 출신이다.

+0

다른 문제가 있습니다. 코드를 사용해 보았습니다.하지만 클래스 경로에 jar 파일을 추가 했음에도 불구하고 여전히 Guava에 상대적인 NoClassDefFoundError를 얻고 있습니다. 오후 8시 30 분 P.S. 실행 중에 만 오류가 발생하면 Java 파일에서 문제를 발견하지 못합니다. 내 나쁜 영어 죄송합니다 – Medioman92

+0

나는 클래스 경로 문제를 해결했지만, 어쨌든 나는 여전히 0 바이트 파일을 다운로드하려고하면 – Medioman92

+0

어디에 문제가있는 것을 발견했습니다 파일 down_file = new File ("log /" + 파일); 절대 경로로 작동하며 상대 경로로 작동하지 않습니다. 왜? – Medioman92

2

를 올바르게 파일을 저장달라고하지만, 항상 0 바이트 파일입니다 : http://commons.apache.org/io/

HereIOUtils.copy()을 참조하십시오.

+0

고맙습니다.이 덕분에 나 또한 도움이되었습니다. 비록 내가 Spring의 [FileCopyUtils] (http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/util/FileCopyUtils.html)를 사용하여 동일하게 달성했다. – Igor

+0

@ GileB glad 도와 드리겠습니다. – davioooh