我有一个由常规文本输入和文件上传组成的表单。
<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>
在portlet类中我想访问上传的文件和参数“name”。我发现当我在我的表单中放入enctype =“multipart / form-data”时,我无法得到其他(这里是“name”参数) request.getParameter(“name”)或 ParamUtil.getString(request,“name”)。
但是当我删除enctype =“multipart / form-data”时,我可以看到“name”参数,但当然错过了上传的文件。我怎样才能同时上传文件和常规参数
编辑: 我的行动实施是:
@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 "";
}
}
答案 0 :(得分:3)
发现当表单是multipart / form-data时,我应该从UploadPortletRequest而不是ActionRequest获得额外的参数(比如“name”)。
获取参数的正确形式:
UploadPortletRequest uploadRequest = PortalUtil
.getUploadPortletRequest(request);
String name = ParamUtil.getString(uploadRequest,"name");
答案 1 :(得分:1)
当您发布到portlet操作时,参数应该命名为portlet。尝试
<input type="text" name="<portlet:namespace/>name"/>
...
<input type="file" name="<portlet:namespace/>imgFile"/>
或者你可以使用aui taglib,例如
<aui:form ...>
<aui:input ... name="name"/>
</aui:form>
此taglib会自动添加命名空间