【问题标题】:getAbsolutePath() like method in UploadedFile(org.apache.myfaces.custom.fileupload.UploadedFile;)类似于 UploadedFile(org.apache.myfaces.custom.fileupload.UploadedFile;) 中的 getAbsolutePath() 方法
【发布时间】:2011-12-09 09:05:55
【问题描述】:

我目前正在开发一个应用程序,在该应用程序中,用户可以选择浏览和上传 excel 文件,但我很难获得所浏览文件的绝对路径。因为位置可以是任何东西(Windows/Linux)。

import org.apache.myfaces.custom.fileupload.UploadedFile;
-----
-----
private UploadedFile inpFile;
-----
getters and setters    
public UploadedFile getInpFile() {
    return inpFile;
} 
@Override
public void setInpFile(final UploadedFile inpFile) {
    this.inpFile = inpFile;
}

我们使用 jsf 2.0 进行 UI 开发,使用 Tomahawk 库进行浏览按钮。

浏览按钮的示例代码

t:inputFileUpload id="file" value="#{sampleInterface.inpFile}" 
        valueChangeListener="#{sampleInterface.inpFile}" />

上传按钮的示例代码

     <t:commandButton action="#{sampleInterface.readExcelFile}" id="upload" value="upload"></t:commandButton>

这里的逻辑

浏览按钮 -> 用户将通过浏览位置来选择文件 上传按钮 -> 点击上传按钮,会触发 SampleInterface 中的 readExcelFile 方法。

示例接口实现文件

public void readExcelFile() throws IOException {

        System.out.println("File name: " + inpFile.getName());
    String prefix = FilenameUtils.getBaseName(inpFile.getName()); 
    String suffix = FilenameUtils.getExtension(inpFile.getName());
        ...rest of the code
            ......
 }

文件名:abc.xls

前缀:abc

后缀:xls

请帮助我获取正在浏览的文件的完整路径(如 c:.....),然后将此绝对路径传递给 excelapachepoi 类,在那里它会被解析并显示/存储内容在 ArrayList 中。

【问题讨论】:

    标签: java jsf tomahawk


    【解决方案1】:

    为什么需要绝对文件路径?你能用这些信息做什么?创建File?抱歉,不,如果网络服务器在物理上与网络浏览器不同的机器上运行,那绝对不可能。再想一想。更重要的是,适当的网络浏览器不会发回有关绝对文件路径的信息。

    您只需根据客户端已经发送的上传文件的内容创建File即可。

    String prefix = FilenameUtils.getBaseName(inpFile.getName()); 
    String suffix = FilenameUtils.getExtension(inpFile.getName());
    File file = File.createTempFile(prefix + "-", "." + suffix, "/path/to/uploads");
    
    InputStream input = inpFile.getInputStream();
    OutputStream output = new FileOutputStream(file);
    
    try {
        IOUtils.copy(input, output);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(input);
    }
    
    // Now you can use File.
    

    另见:

    【讨论】:

    • 感谢 BalusC 的精彩和中肯的解释。我一定是有很大的误会。我的逻辑是当用户浏览文件并单击上传按钮时。它将通过接口触发 readexcel() 函数,然后将文件完整路径发送到将读取和解析文件的 ExcelApache java 类。 fileName =new POIFSFileSystem(new FileInputStream(file));
    • 如果您不关心磁盘上的文件副本,也可以使用new POIFSFileSystem(inpFile.getInputStream())
    • 应该在windows和unix文件系统上都可以工作?该应用程序有一个选项,用户将被要求上传 excel/word 文档文件,用户可以在任何平台上。我只是澄清一下。
    • 是的。毕竟只是一个字节流。
    【解决方案2】:

    我记得过去也遇到过一些问题。如果我没记错的话,我认为您在上传文件时无法获得完整的文件路径。出于安全考虑,我认为浏览器不会告诉您。

    【讨论】:

    • 感谢 Averroes 的回复,我的实际目的是使用 poi 库读取 excel 文件。由于在浏览按钮上的运行时间决定位置,我的理解是发送完整的绝对路径来读取文件。似乎我的“逻辑”在这里缺少“逻辑”:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多