I have a form which consist of a regular text input and a file upload.
<portlet:actionURL var='create' name="addProduct">
</portlet:actionURL>
<form id="addform" action="<%=create%>" method="post" enctype="multipart/form-data">
<dl class="dl-horizontal">
<dt>Product Name</dt>
<dd>
<input type="text" name="name" />
</dd>
<dt>Image File</dt>
<dd>
<input type="file" name="imgFile" >
</dd>
</dl>
<button type="submit">Save</button>
</form>
in the portlet Class I want to access file uploaded and parameter "name". I find out when I put enctype="multipart/form-data" in my form I can't get other(here the "name" parameter) by request.getParameter("name") or ParamUtil.getString(request,"name").
but when I remove enctype="multipart/form-data" I can see the "name" parameter, but of course the uploaded file is missed. how can I have both uploaded file and regular parameter
EDIT: my action implementation is:
@ProcessAction(name = "addProduct")
public void addProduct(ActionRequest request, ActionResponse response) {
String name = ParamUtil.getString(request,"name");
String anotherTryForName = request.getParameter("name");
System.out.println(name);
System.out.println(anotherTryForName);
System.out.println(uploadImg(request));
}
private String uploadImg(ActionRequest request) {
String realPath = getPortletContext().getRealPath("/");
byte[] bytes = null;
try {
UploadPortletRequest uploadRequest = PortalUtil
.getUploadPortletRequest(request);
String sourceFileName = uploadRequest.getFileName("imgFile");
File file = uploadRequest.getFile("imgFile");
try {
bytes = FileUtil.getBytes(file);
} catch (IOException e2) {
e2.printStackTrace();
}
File newFile = null;
if ((bytes != null) && (bytes.length > 0)) {
try {
newFile = new File(realPath + "demo/productimg/"
+ sourceFileName);
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(
newFile);
fileInputStream.read(bytes);
fileOutputStream.write(bytes, 0, bytes.length);
fileOutputStream.close();
fileInputStream.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
} catch (IOException e1) {
System.out.println("Error Reading The File.");
e1.printStackTrace();
}
}
return sourceFileName;
} catch (Exception e) {
System.out.println("Exception::::" + e.getMessage());
return "";
}
}
found that when the form is multipart/form-data I should get extra parameter(like "name") from UploadPortletRequest instead of ActionRequest.
correct form of getting parameter:
UploadPortletRequest uploadRequest = PortalUtil
.getUploadPortletRequest(request);
String name = ParamUtil.getString(uploadRequest,"name");