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

标签 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>

这里的逻辑

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

示例接口(interface)实现文件

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中。

最佳答案

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

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

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.

另请参阅:

关于java - getAbsolutePath() 类似 UploadedFile(org.apache.myfaces.custom.fileupload.UploadedFile;) 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8443246/

相关文章:

java - fragment 中的 OnClickListener 不再起作用

java - 找不到资源 - Android

MySQL YEAR 字段 - 如何从 jsf 输入

java - JSF - 如何从支持 bean 操作方法内部确定当前 JSP 页面

java - 战斧和滚动选项卡

jsf - 我可以在 JSF 2.2 中使用 JSF 2.0 兼容的组件库吗

java - 正则表达式 : search strings extending on exact number of lines

jsf - 通过 'Referer' header 防止跨站点请求伪造

jsf - 操作 CSRF token 后,在 <protected-views> 中声明的 View 仍然可以访问

java - 最小和最大数字