我的 Bean 中有这样的功能:
public String uploadFile(UploadedFile uploadedFile) {
logger.info("Enter: uploadFile(UploadedFile uploadedFile).");
String name = uploadedFile.getName();
String extension = name.substring(name.length() - 3);
if (extension.contentEquals("peg")) {
extension = "jpeg";
}
RandomString rs = new RandomString(RANDOM_PHOTO_NAME_LENGTH);
this.randomPhotoName = rs.nextString();
String fileName = this.randomPhotoName + "." + extension;
logger.info("File name: " + name + ". Extension: " + extension + ". New fileName: " + fileName);
ServletContext sc = (ServletContext) FacesContext.getCurrentInstance()
.getExternalContext().getContext();
File f = new File(
sc.getRealPath(Constant.USER_FILE_PATH));
if (!f.exists()) {
logger.info("Folder "
+ Constant.USER_FILE_PATH
+ " nie istniej. Tworze nowy.");
f.mkdirs();
}
File backupFile = new File(
sc.getRealPath(Constant.USER_FILE_PATH
+ fileName));
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(uploadedFile.getInputStream());
out = new FileOutputStream(backupFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
} catch (IOException ioe) {
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage msg = null;
msg = new FacesMessage(
"Pojawił się nieoczekiwany błąd przy uploadowaniu pliku.");
context.addMessage(null, msg);
logger.error(
"Pojawił się nieoczekiwany błąd przy uploadowaniu pliku.",
ioe);
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info("Exit: uploadFile(UploadedFile uploadedFile).");
return fileName;
}
所有文件都保存在 tmp 目录中,例如:
\jboss-5.1.0.GA\server\default\tmp\a006-czo4uq-gzzu4l42-1-gzzuk7xr-a2\TupTus.war\media\img\user-gallery\6u2fpgu3tkzniwg.JPG