2012-11-28 146 views
1

我有這個問題。 我使用spring,並將附件(doc,pdf,png ...)存儲到服務器文件系統中。 然後我將文件的路徑和名稱保存到我的數據庫中。 現在我怎樣才能讀取這個文件作爲鏈接到瀏覽器?從java文件夾文件系統輸出存儲的文件

我以爲寫文件到網站的位置,並給這個位置的瀏覽器。 這是一個很好的做法嗎? 但是,如何在可視化後刪除文件?

我希望問題很清楚。

enter image description here

寫我用:

/** what write for reach temp-file folder (my project name is intranet) 
    I thougth TEMP_FOLDER=""/intranet/resources/temp-files/"; 
    but It doesnt work. ioexception (The system cannot find the path specified) 
*/ 
final static String TEMP_FOLDER=????? 

public static String createTempFile(String originalPathFile,String fileName){ 
String tempPathFile=""; 
try { 
    InputStream inputStream = new FileInputStream(originalPathFile); 
    tempPathFile=TEMP_FOLDER+fileName; 
    File tempFile = new File(tempPathFile); 

    OutputStream out = new FileOutputStream(tempFile); 
    int read = 0; 
    byte[] bytes = new byte[1024]; 
    while ((read = inputStream.read(bytes)) != -1) { 
     out.write(bytes, 0, read); 
    } 
    out.flush(); 
    out.close(); 
} catch (IOException ioe) { 
    System.out.println("Error while Creating File in Java" + ioe); 
} 

return tempPathFile; 
    } 

回答

2

現在,我怎麼看這個文件作爲鏈接到瀏覽器?

將在你的JSP

<a href="<c:url value="/fileDownloadController/downloadFile?filename=xyz.txt"/>" title="Download xyz.txt"></a> 

在你的控制器以下鏈接:

@Controller 
@RequestMapping("/fileDownloadController") 
public class FileDownloadController 
{ 
    @RequestMapping("/downloadFile") 
    public void downloadFile( 
     @RequestParam String filename, 
     HttpServletResponse response) 
    { 
     OutputStream outputStream = null; 
     InputStream in = null; 
     try { 
      in = new FileInputStream("/tmp/" + filename); // I assume files are at /tmp 
      byte[] buffer = new byte[1024]; 
      int bytesRead = 0; 
      response.setHeader(
       "Content-Disposition", 
       "attachment;filename=\"" + filename + "\""); 
      outputStream = response.getOutputStream(); 
      while(0 < (bytesRead = in.read(buffer))) 
      { 
       outputStream.write(buffer, 0, bytesRead); 
      } 
     } 
     finally 
     { 
      if (null != in) 
      { 
       in.close(); 
      } 
     } 

    } 
} 
+0

是!!!!太好了!!!謝謝!... – Shinigami

1

另一個答案,可以爲人們進入這個問題,使用IOUtils有用:

IOUtils.copy(new FileInputStream("filename"), outputStream);