2012-08-01 31 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; 
} 

我在哪裏做錯了? 當我下載按鈕單擊它正確地問我要保存文件,但它始終是一個0字節的文件...

+1

'down_file.canRead()'返回true嗎? – Xaerxess 2012-08-01 16:01:35

+0

是的,它返回true – Medioman92 2012-08-01 16:09:12

回答

5

這應該做的工作:

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; 
} 

其中ByteStreams.copy來自精彩Google's Guava library

編輯

另外,如果你在使用Spring 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[]@ResponseBody註解的任何@Controller方法。閱讀更多herehere

Files.toByteArray也來自Guava。

+0

我有另一個問題,我試過你的代碼,但我仍然得到一個相對於番石榴的NoClassDefFoundError,儘管我已經在類路徑中添加了jar。 P.S.錯誤只在運行時出現,java文件沒有注意到任何問題。 對不起我的英文不好 – Medioman92 2012-08-02 08:05:43

+0

我解決類路徑問題,但無論如何,i'mm仍然得到0字節的文件時,試圖下載 – Medioman92 2012-08-02 08:13:48

+0

我已經找到了問題的所在, 文件down_file =新的文件(「登錄/」 +文件); 它具有絕對路徑,相對路徑不起作用,爲什麼? – Medioman92 2012-08-02 08:39:01

2

與嘗試:

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

,你可以在這裏找到的Apache下議院IO: http://commons.apache.org/io/

Here您找到IOUtils.copy()的參考文獻。

+0

Thanx,這也幫助了我。儘管我使用Spring的[FileCopyUtils](http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/util/FileCopyUtils.html)來實現相同的 – Igor 2013-01-25 11:45:00

+0

@GileB很高興以幫助:) – davioooh 2013-01-25 14:12:37