【发布时间】:2025-12-01 07:15:01
【问题描述】:
我正在尝试创建超链接以从网络驱动器 G 中打开文件:
这是我的测试 servlet 的一部分:
@WebServlet(name="fileHandler", urlPatterns={"/fileHandler/*"})
public class FileServlet extends HttpServlet
{
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String requestedFile = request.getPathInfo();
...
File file = new File("G:/test_dir", URLDecoder.decode(requestedFile, "UTF-8")); // cesta se nacita v kazdem doGet
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);
}
}
}
我的 HTML 组件:
<a href="fileHandler/test.txt">TEST FILE</a>
网络驱动器在应用服务器上映射为G:\
在我的 localhost 应用服务器上一切正常。我可以从本地驱动器 C: 甚至从同一个网络驱动器 G: 打开文件。
当我在真实服务器上启动 JSF 应用程序时,我只能从本地驱动器打开文件。 不是来自 G: drive。
我尝试了简单的JAVA 应用程序(以查找 java 实例是否可以访问网络驱动器)并且它可以在两者(服务器和 dev.PC)上运行:
public class Test
{
static void main(String[] args)
{
String path = "G:/test_dir/test.txt";
File file = new File(path);
System.err.println(file.exists() ? "OK" : "NOK");
}
}
我尝试了不同的 URI 方案:
G:/test_dirG:\\test_dir
以下根本不起作用:
file://server/g:/test_dir///server/g:/test_dir-
\\\\server\\g\\test_dir---> 事实上,这应该可以工作
我的开发PC和应用服务器应该有什么区别?
解决方案:
我发现links to network drive doesn't work in standalone Tomcat, but works in Eclipse + Tomcat,所以我必须使用完整的URI:
- 案例 Eclipse + Tomcat:路径
G:/test_dir/test.txt有效 - 案例独立 Tomcat:路径
\\\\server\\g\\test_dir\\test.txt有效
【问题讨论】:
-
你试过服务器上的简单测试应用以及你的开发盒吗?
-
是的,两者都适用
-
在这种情况下,检查
URLDecoder.decode(requestedFile, "UTF-8")的结果可能是可行的——也许这会给你一个不存在的文件名 -
我尝试打印路径,在所有情况下似乎都可以:-/ Java 安全性似乎还可以,G: 已映射.. 很奇怪