Upload Files with JSF and MyFaces
The MyBean Class
The backing bean has three properties: myFile,
myParam, and myResult. The role of the
myFile property was explained in the first half of the
article. It lets you get the content of the uploaded file along
with its name, size, and content type. The value of the
myParam property is the message-digest algorithm. The
myResult property will hold the hash value after the
execution of the processMyFile() method. The
MyBean class provides get and set methods for all of its
properties:
package com.devsphere.articles.jsfupload;
import org.apache.myfaces.custom.fileupload.UploadedFile;
...
public class MyBean {
private UploadedFile myFile;
private String myParam;
private String myResult;
public UploadedFile getMyFile() {
return myFile;
}
public void setMyFile(UploadedFile myFile) {
this.myFile = myFile;
}
public String getMyParam() {
return myParam;
}
public void setMyParam(String myParam) {
this.myParam = myParam;
}
public String getMyResult() {
return myResult;
}
public void setMyResult(String myResult) {
this.myResult = myResult;
}
...
}
The processMyFile() method gets the content of the
uploaded file through an input stream obtained with
myFile.getInputStream(). The hash value is computed
with the help of java.security.MessageDigest, and then
it is converted into a string that can be accessed via the
myResult property:
package com.devsphere.articles.jsfupload;
...
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.*;
public class MyBean {
...
public String processMyFile() {
try {
MessageDigest md
= MessageDigest.getInstance(myParam);
InputStream in = new BufferedInputStream(
myFile.getInputStream());
try {
byte[] buffer = new byte[64 * 1024];
int count;
while ((count = in.read(buffer)) > 0)
md.update(buffer, 0, count);
} finally {
in.close();
}
byte hash[] = md.digest();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
int b = hash[i] & 0xFF;
int c = (b >> 4) & 0xF;
c = c < 10 ? '0' + c : 'A' + c - 10;
buf.append((char) c);
c = b & 0xF;
c = c < 10 ? '0' + c : 'A' + c - 10;
buf.append((char) c);
}
myResult = buf.toString();
return "OK";
} catch (Exception x) {
FacesMessage message = new FacesMessage(
FacesMessage.SEVERITY_FATAL,
x.getClass().getName(), x.getMessage());
FacesContext.getCurrentInstance().addMessage(
null, message);
return null;
}
}
}
Prev [1] [2] [3] [4] [5] [6] Next