Enable the Struts 2 file upload feature
We can take full advantage of the WebSphere Commerce Struts 2 file upload feature. In order to use Struts 2 uploads, ensure that you have enabled the capability.
About this task
Struts 2 file upload is supported in WebSphere Commerce. This feature uses the file upload interceptor to fulfill requests. For details, see https://struts.apache.org/core-developers/file-upload.html.
Procedure
- In any JSPs that request file uploads, specify the enctype as “multipart/form-data” and the action name as follows:
<form enctype="multipart/form-data" method="post" name="uploadForm" action="ContractUpload" target="NAVIGATION" id="uploadForm"> ... <input name="fileUpload" type="file" size="50" id="ContractImportPanel_FormInput_filename_In_uploadForm_1" /> ... </form>
Note: We can use Struts 2 standard tags as well.
- Define the action in the Struts configuration file.
<action class="com.ibm.commerce.struts.v2.BaseAction" name="ContractUpload"> ... <param name="parameter">your_own_command </param> </action>
Note: If the class called in the action is BaseAction, we can use it in our own commands by including the following code snippets, since it has already helped incorporate the uploaded file parameters into the request properties.
UploadedFile uploadedFile = null; TypedProperty reqProperties = (TypedProperty) request.getAttribute(ECConstants.EC_DECRYPTEDREQPROP); Object uploadedFileObj = reqProperties.get(ECConstants.EC_UPLOADED_FILE, null); if (uploadedFileObj != null) { uploadedFile = (UploadedFile) reqProperties.get(ECConstants.EC_UPLOADED_FILE); }
- Write a new action to fetch the uploaded file information.
import java.io.File; import com.opensymphony.xwork2.ActionSupport; public class BaseAction extends ActionSupport { private File file; private String contentType; private String filename; public void setFileUpload(File file) { this.file = file; } public void setFileUploadContentType(String contentType) { this.contentType = contentType; } public void setFileUploadFileName(String filename) { this.filename = filename; } public String execute() { //... return SUCCESS; } }
Note: The highlighted terms in the set methods should exactly match the name of the file. If the action is extended from BaseAction, call the corresponding super-method to set the file information. (In BaseAction, it can only consume a file whose name is filename.)
public void setFileUpload(File file) { super.setFilename(file); this.file = file; } public void setFileUploadContentType(String contentType) { super.setFilenameContentType(contentType); this.contentType = contentType; } public void setFileUploadFileName(String filename) { super.setFilenameFileName(filename); this.filename = filename; } public String execute() { //... return SUCCESS; } }