Skip to content

Instantly share code, notes, and snippets.

@icemagno
Last active August 29, 2015 14:01
Show Gist options
  • Save icemagno/054ce3ab329aa1f59db4 to your computer and use it in GitHub Desktop.
Save icemagno/054ce3ab329aa1f59db4 to your computer and use it in GitHub Desktop.
Upload files with Java and Struts2

This document shows how to upload a photo by using Struts2 action. Things to note:

The HTML form must have

enctype="multipart/form-data" method="POST"

Your S2 Action must have the attributes to receive the raw file and the file name. The raw file attibute name is the same you created in HTML form and the file name attribute is that name plus "FileName" word.

<input name="myPhoto" type="file" >
private File myPhoto;
private String myPhotoFileName;

Just create a File "destiny" to desired path and copy "myPhoto" to "destiny".

Piece of cake.

<html>
<body>
<form enctype="multipart/form-data" method="POST" id="frmConfig" action="doConfig">
<input name="myPhoto" type="file" >
</form>
</body>
</html>
package cmabreu.action;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
@Action (value = "doConfig", results = { @Result (location = "index_login.jsp", name = "ok")} )
@ParentPackage("default")
public class DoConfigAction {
private File myPhoto;
private String myPhotoFileName;
public String execute () {
ServletContext context = ServletActionContext.getServletContext();
String path = context.getRealPath("") + "/img/photos/";
File destiny = new File(path, myPhotoFileName);
try {
FileUtils.copyFile(myPhoto, destiny);
} catch ( Exception e) {
// Some IO error
}
}
... Setters and Getters
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment