getAbsolutePath()与UploadedFile中的方法类似(org.apache.myfaces.custom.fileupload.UploadedFile;)

时间:2011-12-09 09:05:56

标签: java jsf tomahawk

我目前正在开发一个应用程序,用户可以选择浏览和上传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>

逻辑

浏览按钮 - &gt;用户将通过浏览位置选择文件 上传按钮 - &gt;在单击上传按钮时,它将在SampleInterface中触发方法readExcelFile。

SampleInterface实施文件

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。

2 个答案:

答案 0 :(得分:2)

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

您只需根据客户已发送的已上传文件的内容创建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.

另见:

答案 1 :(得分:0)

我记得过去也有这个问题。如果我没有弄错,我认为上传文件时无法获得完整的文件路径。我认为浏览器不会出于安全目的告诉你。