私は以前に同じ問題に直面していました。ユーザーが参照ボタンをクリックしたときにポップアップを開くことで問題を解決しました。この新しいポップアップは、ファイルのアップロードとダウンロードをサポートするサーブレットに直接リンクされていました。ファイルがアップロードされると、ポップアップはサーブレット本体のロード時に 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>
これはサーブレットに送信され、サーブレットは画像をレンダリングして特定の場所に保存します。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>");
}
このサーブレットは、構成された場所でのファイルの保存が完了すると、以前に開いていたポップアップを直接閉じます。
このようにして、管理対象の Bean である jsf 1.2 を使用して、フィールドのアップロードを実現できました。stackoverflow で他の方法を見つけましたが、実装が少し複雑だと感じました。