Thursday, March 10, 2011

Struts File Upload

http://wiki.apache.org/struts/StrutsFileUpload

in a nutshell:


in the JSP:


in the Action:

ProductUploadForm myForm = (ProductUploadForm) form;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");



// Process the FormFile
FormFile myFile = myForm.getTheFile();
String contentType = myFile.getContentType();
String fileNameAbsolutePath    = myFile.getFileName();
int fileSize       = myFile.getFileSize();

logger.debug("uploading File Name: " + fileNameAbsolutePath + ", File Size: " + fileSize + ", contentType: " + contentType);
String fileName = new File(fileNameAbsolutePath).getName();
String newFileName = STAGING_DIR + fileName + sdf.format(new Date());

try {
 // copy the stream content to a File in a staging directory, adding timestamp to the file name
 File f2 = new File(newFileName);
 OutputStream out = new FileOutputStream(f2);
 InputStream in = myFile.getInputStream();
 byte[] buf = new byte[1024];

 int len;

 while ((len = in.read(buf)) > 0){
  out.write(buf, 0, len);
 }
 in.close();
 out.close();
 logger.debug("finished copying File Name: " + fileNameAbsolutePath);
} catch (Exception e) {
 logger.error("problem uploading file name : " + fileNameAbsolutePath, e);
}




and the Form contains an attribute
private org.apache.struts.upload.FormFile theFile;

with getter and setter

No comments: