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