adf中用inputFile上传文件到weblogic 方法1

上传文件有两种,一是直接上传文件到到服务器的某个路径下 二是直接上传文件内容到数据库

这里首先是上传到路径下实例

由于weblogic中获得路径只能用getServletContext().getResource("/").getPath(),有没有其它方法我不知道。我只知道不能用getRealPath()

问题描述:在tomcat服务器和webspare服务器,以这样的方式都能够得到完整的服务器路径,

但迁移到weblogic之后,就得不到了,返回的就是null!

原因:weblogic是以war包的形式发布的,并没有realPath,故不能用 getServletContext().getRealPath("/")获得绝对路径!

解决办法:修改代码获得相对路径:

把代码getServletContext().getRealPath("/") 修改成 getServletContext().getResource("/")既可以解决此问题!

实例如下

<af:form id="f1" usesUpload="true">
<af:inputFile label="文件名:" id="if1"
valueChangeListener="#{MyBackingBean.valueListener}"
binding="#{MyBackingBean.fileUI}" autoSubmit="true"
value="#{MyBackingBeanBean}"/>
<af:commandButton text="upload" id="cb1"
actionListener="#{MyBackingBean.commonListener}"/>
</af:form>

注意 autoSubmit="true"没有设置,属性监听器就没作用

private RichInputFile fileUI;
private String fileLocation = "/upload";
private UploadedFile uploadedFile;

public void valueListener(ValueChangeEvent valueChangeEvent) {
// Add event code here...
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletRequest request =(HttpServletRequest)externalContext.getRequest();
String root = "";
try {
root =request.getSession().getServletContext().getResource("/").getPath();
} catch (MalformedURLException e) {
}
if (!new File(root + fileLocation).exists()) {
new File(root + fileLocation).mkdirs();
}
UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue();
if (file != null && file.getLength() > 0) {
try {
InputStream in = file.getInputStream();
FileOutputStream out =
new FileOutputStream(root + fileLocation + "/" +
file.getFilename());
writeInputStreamToOutputStream(in, out);
in.close();
out.close();

String message =
"Successfully uploaded file '" + file.getFilename() +
"' (" + file.getLength() + " bytes)";
System.out.println(message);
} catch (FileNotFoundException fnfe) {
// TODO: Add catch code
fnfe.printStackTrace();
} catch (IOException ioe) {
// TODO: Add catch code
ioe.printStackTrace();
}
}
}

你可能感兴趣的:(weblogic)