JSF应用程序:打开文件,而不是下载它

时间:2013-10-05 06:15:34

标签: java jsf-2

当前情况:我正在尝试创建一个JSF app(portlet),其中应包含指向存储在其中的Excel文件(xlsxlt)的链接为我们公司的所有用户映射的公共网络驱动器G:。主要目标是统一对这些文件的访问,并将工作保存到用户,以便在G盘上的某个地方搜索报告。我希望很清楚..?

我正在使用以下servlet打开文件。问题是,它不仅仅是打开,而是通过浏览器下载,然后打开:

@WebServlet(name="fileHandler", urlPatterns={"/fileHandler/*"})
public class FileServlet extends HttpServlet 
{
  private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
  private String filePath;

  public void init() throws ServletException  {
    this.filePath = "c:\\Export";
    System.out.println("fileServlet initialized: " + this.filePath);
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
  {
    String requestedFile = request.getPathInfo();
    File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));
    String contentType = getServletContext().getMimeType(file.getName());

    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
      input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
      output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

      byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
      int length;

      while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
      }
    } finally { 
      close(output);
      close(input);
    }
  }

  private static void close(Closeable resource) {
    if (resource != null) resource.close();
  }
}

如何启动相应的应用程序(例如ExcelWord等)点击链接(使用绝对文件路径)并在原始位置打开文件?

更新:我正在尝试使用<a>代码:

<a href="/G:/file.xls">File</a> // various "/" "\" "\\" combinations
<a href="file:///G:/file.xls">File</a>

但它不起作用:

type Status report
message /G:/file.xls
description The requested resource is not available.

1 个答案:

答案 0 :(得分:3)

大多数浏览器都会将文件URL视为安全风险,因为它们会导致文件在网页上的客户端计算机上打开,而最终用户却无法识别它。如果你真的想这样做,你必须配置浏览器以允许它。

请参阅wikipedia article了解解决方案。

相关问题