从服务器下载文件

时间:2018-04-03 08:28:14

标签: java file download fileinputstream

我试图下载我在服务器上的文件。 如果我在本地运行我的应用程序一切正常,我可以下载文件。此外,我可以从浏览器或Windows文件浏览器下载该文件。 但是,当我将我的应用程序上传到我的服务器时,我无法获取该文件。

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

2 个答案:

答案 0 :(得分:1)

哪个服务器 - Linux,Windows等。在Linux环境中,它的路径应设置为正斜杠,例如/ opt / something / yourfile。另外,请记录文件路径以了解您正在查找的文件的运行时位置,这将有助于您了解问题的原因。

答案 1 :(得分:0)

最后,我解决了改变文件路径的问题,具体取决于我是在Windows还是Linux上工作。 我还将文件移动到另一个文件夹,因为我似乎没有权限在我的文件夹中。 而且我不得不改变我阅读文件的方式,因为当我下载文件时我得到了错误“错误:网络错误” 现在我正在阅读apache commons:

 FileUtils.copyFile(file, response.getOutputStream());