我以前也遇到过同样的问题。我通过在用户单击浏览按钮时打开一个弹出窗口解决了这个问题,这个新的弹出窗口直接链接到一个支持文件上传和下载的 servlet。上传文件后,servlet 在加载 servlet 主体时调用 window.close() 直接关闭弹出窗口。以下是所做的更改:
在提示用户输入文件的 addItem.jsp 中:
<script type="text/javascript">
...
function newWindow()
{
popupWindow = window.open('addItemImage.jsp','name','width=200,height=200');
}
...
</script>
<f:view>
<h:form id="search" onsubmit="return validateDetails()">
...
<h:panelGroup>
<font color="black">Item Image :</font>
</h:panelGroup>
<h:panelGroup>
<input type="button" value="Upload Image" onClick="newWindow()"/>
</h:panelGroup>
...
</h:form>
</f:view>
在打开的新弹出窗口中:addItemImage.jsp
<script type="text/javascript">
function validate()
{
var file = document.getElementById("file").value;
if(file == null || file == "")
return true;
if(file.indexOf(".jpg") == -1 && file.indexOf(".gif") && file.indexOf(".bmp") == -1 && file.indexOf(".jpeg") == -1)
{
alert("Invalid File Format!! Please upload jpg/bmp/gif");
return false;
}
return true;
}
</script>
<body>
<form enctype="multipart/form-data" method="post" action="FileUploaderServler.view" onsubmit="return validate()">
<input type="file" name="file" id="file" />
<input type="submit" value="Upload Image">
</form>
</body>
这将发布到一个 servlet,然后该 servlet 将呈现图像并将其保存在一个地方。FileUploaderServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
List<FileItem> items = null;
try
{
MultipartHTTPServletRequest multipartHTTPServletRequest = new MultipartHTTPServletRequest(Connection.getRequest());
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartHTTPServletRequest);
}
catch (FileUploadException e)
{
e.printStackTrace();
}
if(!Util.isNullList(items))
{
for (FileItem item : items)
{
if (!item.isFormField())
{
String itemName = item.getFieldName();
InputStream filecontent = null;
try
{
filecontent = item.getInputStream();
}
catch (IOException e)
{
e.printStackTrace();
}
/* String currDirPath = System.getProperty("user.dir"); // C:\Users\KISHORE\Desktop\eclipse
File file = new File(currDirPath+"\\itemImages");*/
new File(Constants.ABS_FILE_PATH_TO_IMAGES).mkdir();
File fw = new File(Constants.ABS_FILE_PATH_TO_IMAGES+"\\"+Connection.getRequest().getSession().getId()+".jpg"); // E:\Kishore Shopping Cart\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ShoppingCart\WEB-INF\itemImages\EC34EEE58065AD674192D3D57124F07E.jpg
fw.delete();
fw.createNewFile();
try
{
item.write(fw);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
PrintWriter out = response.getWriter();
out.print("<html><title>Add Image to Item</title><body onload='window.close()'>Uploaded Successfully!!</body>");
System.out.print("</html>");
}
此 servlet 在配置完成保存文件后,将直接关闭先前打开的弹出窗口。
所以这样我就可以使用托管bean,jsf 1.2并实现字段上传。我在stackoverflow上找到了其他方法,但觉得实现起来有点复杂。