Java 从服务器下载文件
我正在尝试下载服务器上的文件。 如果我在本地运行我的应用程序,一切正常,我可以下载文件。此外,我还可以从浏览器或Windows文件资源管理器下载该文件。 但是,当我将应用程序上载到服务器时,我无法获取该文件Java 从服务器下载文件,java,file,download,fileinputstream,Java,File,Download,Fileinputstream,我正在尝试下载服务器上的文件。 如果我在本地运行我的应用程序,一切正常,我可以下载文件。此外,我还可以从浏览器或Windows文件资源管理器下载该文件。 但是,当我将应用程序上载到服务器时,我无法获取该文件 try { uri = "\\DEVDOCSERVER\DOCUMENTS\sample.xml"; if(uri.contains(".") ) { String extension = uri.substring(uri.last
try {
uri = "\\DEVDOCSERVER\DOCUMENTS\sample.xml";
if(uri.contains(".") ) {
String extension = uri.substring(uri.lastIndexOf("."));
File file = new File(uri);
if(file!=null)
logger.error("file size: " + file.length());
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
String fileName = getFileName(uri);
logger.error("file name: " + fileName);
String contentType = "application/octet-stream";
response.setContentType(contentType);
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
response.setContentLength((int) file.length());
ServletOutputStream out = null;
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[1024];
out = response.getOutputStream();
int i = 0;
while ((i = input.read(buffer)) != -1) {
out.write(buffer);
out.flush();
}
if(input!=null)
logger.error("file input: " + input.toString());
FacesContext.getCurrentInstance().responseComplete();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
}
} catch (InternacionalizacionFwException e) {
e.printStackTrace();
}
当我检查日志时,我得到下一个错误:没有这样的文件或目录,文件大小为0哪个服务器-Linux、Windows等。在Linux环境中,其路径应设置为正斜杠,例如/opt/something/yourfile。另外,请记录文件路径以了解您正在查找的文件的运行时位置,这将帮助您了解问题的原因 最后,我解决了根据我是在Windows还是Linux上工作而更改文件路径的问题。 我还将该文件移动到了另一个文件夹,因为我似乎没有权限访问我所在的文件夹。 我不得不改变我读取文件的方式,因为我在下载文件时遇到了一个错误:网络错误 现在我正在阅读apache commons:
FileUtils.copyFile(file, response.getOutputStream());
服务器的路径是什么?你改变路径了吗?我有两台服务器,一台用于我的应用程序,另一台用于文档,但在同一个网络中,有两台服务器看到了这一点;另一台服务器上的文件不是本地资源。也许您可以创建一个simlink,然后将该文件视为本地文件。但我不在documents server中,因此无法像这样访问file:///C:/f...Thanks! 我在Windows计算机上工作,我的服务器是Linux,所以我上传时必须更改url