我正在尝试创建超链接以打开网络驱动器 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:\
在我的本地主机应用程序服务器上一切正常。我可以从本地驱动器 C: 甚至同一网络驱动器 G: 打开文件。
当我在真实服务器上启动 JSF 应用程序时,我只能从本地驱动器打开文件。 不是来自 G: 驱动器。
我尝试过简单的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_dir
G:\\test_dir
以下根本不起作用:
文件://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
works - 案例独立 Tomcat:路径
\\\\server\\g\\test_dir\\test.txt
有效
最佳答案
如果您可以调试服务器并查看日志,请尝试以下操作:
String requestedFile = request.getPathInfo();
log.debug('requestedFile='+requestedFile);
String decodedFilename = URLDecoder.decode(requestedFile, "UTF-8");
log.debug('decodedFilename='+decodedFilename);
File dir = new File("G:/test_dir");
log.debug('File g:/test_dir is a dir:'+dir.isDirectory());
File file = new File(dir, decodedFilename);
log.debug('requested file = '+file.getAbsolutePath());
log.debug('file exists = '+file.isFile());
如果您没有设置日志框架,可以使用System.out.println()
而不是log.debug()
,但不建议这样做供生产使用。
这不会解决您的问题,但您将能够看到发生了什么。
关于java - 从网络驱动器打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32970810/