Hi, I am trying to upload a jpg image using Struts2 but no luck till now. It
will be great if someone could help me in moving further.
I am using Struts 2.0.8 and i have commons-fileupload-1.2.jar and
commons-io-1.3.2.jar in classpath
My code looks like below.
MyPhoto.jsp
<s:form method="post" action="myPhotoUpload" enctype="multipart/form-data">
<s:file name="myPhoto" cssClass="textbox1" accept="image/*" />
<s:submit name="method:upload" cssClass="btn" value="Upload" />
</s:form>
Action class: MyPhotoUploadAction.java
private File myPhoto;//The actual file
private String myPhotoContentType; //The content type of the file
private String myPhotoFileName; //The uploaded file name
public File getMyPhoto() {
return myPhoto;
}
public void setMyPhoto(File myPhoto) {
System.out.println("Inside setMyPhoto");
this.myPhoto = myPhoto;
}
public String getMyPhotoContentType() {
return myPhotoContentType;
}
public void setMyPhotoContentType(String myPhotoContentType) {
System.out.println("Inside setMyPhotoContentType");
this.myPhotoContentType = myPhotoContentType;
}
public String getMyPhotoFileName() {
System.out.println("Inside getMyPhotoFileName:"+myPhotoFileName);
return myPhotoFileName;
}
public void setMyPhotoFileName(String myPhotoFileName) {
System.out.println("Inside setMyPhotoFileName:"+myPhotoFileName);
this.myPhotoFileName = myPhotoFileName;
}
public String upload() {
try{
System.out.println("Inside Upload");
File destDir = new File("images/member");
System.out.println("File Name:"+this.getMyPhotoFileName());
System.out.println("File
ContentType:"+this.getMyPhotoContentType());
FileUtils.copyFileToDirectory(getMyPhoto(), destDir);
return SUCCESS; // redirect to welcome page.
}catch(Exception exp){
LOG.error("File Upload Error:"+ exp);
this.addActionError("File Upload Error:"+ exp);
return ERROR;
}
}