In Struts 2 file uploading can done with the help of built-in FileUploadInterceptor. We use <s:file> tag to create a file upload component, which allow users to select file from their local disk and upload it to the server. The encoding type of the form should be set to multipart/form-data and the HTTP method should be set to post. The Struts 2 File Upload Interceptor is based on MultiPartRequestWrapper, which is automatically applied to the request if it contains the file element. Then it adds the following parameters to the request
** UPDATE: Struts 2 Complete tutorial now available here.
(assuming the uploaded file name is uploadDoc).
[uploadDoc]File – Will store the actual uploaded File
[uploadDoc]ContentType : This String will store the content type of the file
[uploadDoc]FileName : This String will store the actual name of the uploaded file (not the HTML name)
In the action class you can get the file, the uploaded file name and content type by just creating getter and setters.
private File uploadDoc;
This will store actual uploaded File
private String uploadDocFileName;
This string will contain the file name of uploaded file.
private String uploadDocContentType;
This string will contain the Content Type of uploaded file.
The file upload interceptor also does the validation and adds errors. These error messages are stored in the struts-messsages.properties file. The values of the messages can be overridden by providing the text for the following keys:
struts.messages.error.uploading – error when uploading of file fails
struts.messages.error.file.too.large – error occurs when file size is large
struts.messages.error.content.type.not.allowed – when the content type is not allowed
The problem with above code snippet is, you cannot see the uploaded file in the target folder. Also the file uploaded wont have any proper extension, instead it will have the extension as .tmp.
Struts 2 – Upload File to Desire Folder Location
So in-order to upload and save a file in target space and in-order to have a file with proper extension, i.e .pdf , .doc etc, we should use the following code snippet in the action class’s execute method.
Modified execute method
public String execute()
// Location to store the uploaded file in our desired path
String targetPath = "D:/file target/";
File fileToCreate = new File(targetPath, uploadDocFileName);
catch (IOException e)