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();
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值