2012-11-28 253 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);