1. 上传到服务器的某个目录下
(1)页面代码
方式一:
<af:form usesUpload="true">
<af:inputFile label="Upload:"valueChangeListener="#{managedBean.fileUploaded}"/>
<af:commandButton text="Begin"/>
</af:form>
方式二:
<af:form usesUpload="true">
<af:inputFile label="Upload:" value="#{managedBean.file}"/>
<af:commandButton text="Begin" action="#{managedBean.doUpload}"/>
</af:form>
(2)ManageBean 代码
对应方式一:
private RichInputFile if1;
public void setIf1(RichInputFile if1) {
this.if1 = if1;
}
public RichInputFile getIf1() {
return if1;
}
public void fileUploaded(ValueChangeEvent event) {
InputStream in;
FileOutputStream out;
UploadedFile file = (UploadedFile)event.getNewValue();
String fileUploadLoc = "C:/Temp";
boolean exists = (new File(fileUploadLoc)).exists();
if (!exists) {
(new File(fileUploadLoc)).mkdirs();
}
if (file != null && file.getLength() > 0) {
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage message =
new FacesMessage("File Uploaded" + file.getFilename() + "(" +
file.getLength() + "bytes)");
context.addMessage(event.getComponent().getClientId(context),
message);
try {
out = new FileOutputStream(fileUploadLoc + "/" + file.getFilename());
in = file.getInputStream();
for (int bytes = 0; bytes < file.getLength(); bytes++) {
out.write(in.read());
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
String filename = file != null ? file.getFilename() : null;
String byteLength = file != null ? "" + file.getLength() : "0";
}
if1.setValue(null);
}
对应方式二:
import org.apache.myfaces.trinidad.model.UploadedFile;
public class AManagedBean{
public UploadedFile getFile(){
return _file;
}
public void setFile(UploadedFile file){
_file = file;
}
public String doUpload(){
UploadedFile file = getFile();
// ... and process it in some way}
private UploadedFile _file;
}
doUpload方法与fileUploaded方法类似,故略。
2. 上传到数据库BLOB字段中
请参考《使用ADF BC存取BLOB数据》。
3. 上传文件最大默认限制为2M,可以修改web.xml增大大小,增加如下设置:
<context-param>
<!-- Maximum memory per request (in bytes) -->
<param-name>org.apache.myfaces.trinidad.UPLOAD_MAX_MEMORY</param-name>
<!-- Use 500K -->
<param-value>512000</param-value>
</context-param>
<context-param>
<!-- Maximum disk space per request (in bytes) -->
<param-name>org.apache.myfaces.trinidad.UPLOAD_MAX_DISK_SPACE</param-name>
<!-- Use 5,000K -->
<param-value>5120000</param-value>
</context-param>
<context-param>
<!-- directory to store temporary files -->
<param-name>org.apache.myfaces.trinidad.UPLOAD_TEMP_DIR</param-name>
<!-- Use a TrinidadUploads subdirectory of /tmp -->
<param-value>/tmp/TrinidadUploads/</param-value>
</context-param>
ADF上传
最新推荐文章于 2023-12-12 10:49:20 发布