IT is Fun

October 26, 2007

Upload File – Struts, JSP

Filed under: Java — themamakcorner @ 8:27 am

At the JSP

<html-el:file size=”50″ name=”xxxActionForm” property=”uploadedFile”/>

AT THE ACTION FORM

private FormFile theFile;

private String templateContent;
public FormFile getTheFile() {
return theFile;
}

public void setTheFile(FormFile theFile) {
this.theFile = theFile;
}

public String getTemplateContent()

{

return templateContent;

}

public void setTemplateContent(String templateContent)

{

this.templateContent =templateContent;

}

AT ACTION CLASS

public String doAdd(xxxActionForm actionForm) throws Exception{

try{

String data = “”;
FormFile file = actionForm.getUploadedFile();
//read file
InputStream stream = file.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//get the file size
int size = file.getFileSize();
//define the byte size
byte buffer[] = new byte[size];
int bytesRead = 0;
//read the input
while( (bytesRead = stream.read(buffer, 0, size)) != -1 )
{
baos.write( buffer, 0, bytesRead );
}
//assign it to string
data = new String( baos.toByteArray() );
//store string to setter
actionForm.setTemplateContent(data);
stream.close();
baos.close();
//saving into DB

….

}

catch(Exception e)

{}

return “XXX_PAGE”;

}

Older Posts »

Blog at WordPress.com.