I'm using fileuplod primefaces. I have 3 buttons. Every button is responsible for uploading a file. My first steep is to use 3 methods on my bean to upload every file. Is there a way to make the same method for all types? Every file has his own directory.
<h:form enctype="multipart/form-data" style="height:125px;width:75px;">
<p:fileUpload auto="true"
fileUploadListener="#{composantbean.handleFileUpload(???,1)}"
sizeLimit="2097152"
label="Choose"
allowTypes="/(\.|\/)(pdf)$/"
description="Images"/>
</h:form>
On my managed bean, I'm thinking of this solution:
public void handleFileUpload(FileUploadEvent event,int i) {
String lienPDN =destination+"PDN\\"+FilenameUtils.getName(event.getFile().getFileName());
File result = new File(lienPDN);
try {
FileOutputStream fileOutputStream = new FileOutputStream(result);
byte[] buffer = new byte[BUFFER_SIZE];
int bulk;
InputStream inputStream = event.getFile().getInputstream();
while (true) {
bulk = inputStream.read(buffer);
if (bulk < 0) {
break;
}
fileOutputStream.write(buffer, 0, bulk);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close();
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName()+ " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
selcetitem.setLienPdn(lienPDN);
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,"The files were not uploaded!", "");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
I think a better way might be to implements three handleFileUpload()
methods. Each can handle their unique code (e.g. passing the right filepath). From there you can call a private void wrapUpUpload(String path, (...))
.
Most of all this keeps your code readable. If also prevents the need for changing the default implementation of handleFileUpload()
.
E.g.: make sure to replace 1
, 2
, 3
with something meaningful
void handleFileUpload1(FileUploadEvent event) {
String path = "/uploads/1/";
wrapUpUpload(path);
}
void handleFileUpload2(FileUploadEvent event) {
String path = "/uploads/2/";
wrapUpUpload(path);
}
void handleFileUpload3(FileUploadEvent event) {
String path = "/uploads/3/";
wrapUpUpload(path);
}
private void wrapUpUpload(String path, (...)) {
// Upload the file
}