我在glassfish-web.xml
中为Glassfish制作了备用文档根目录:
<glassfish-web-app>
<property name="alternatedocroot_1" value="from=/Database/* dir=c:/GetSome" />
</glassfish-web-app>
JS上传文件,如果成功,则加载带有上传文件的jsp:
function Changed_inputFileLogo()
{
/*console.log("function Changed_inputFileLogo");*/
current = event.target;
var data = new FormData();
$.each(current.files, function(key, value)
{
data.append(key, value);
});
data.append("idOrganization", _Organization.id);
data.append("requestPage", true);
$.ajax({
type: 'POST',
async: false,
url: 'UploadLogo',
data: data,
processData: false,
contentType: false,
success: function(response)
{
_Organization.logo = 1;
$.ajax({
type: 'POST',
async: false,
url: 'PhotoExist.jsp',
data: "path=" + "Database/LogoOrganization/"+_Organization.id+".jpg",
success: function(response)
{
$("#divLogo").html(response);
},
error: function(xhr, textStatus, errorThrown)
{
LogConsole_ajaxError(xhr, textStatus, errorThrown);
}
});
},
error: function(xhr, textStatus, errorThrown)
{
LogConsole_ajaxError(xhr, textStatus, errorThrown);
}
});
}
这是PhotoExist.jsp文件:
...
<% String path = request.getParameter("path");%>
...
<div class="divPhotoWrapper HavePhoto" onmouseover="ShowPhotoButton()" onmouseout="HidePhotoButton()">
<div class="divDeletePhoto displayNone">
<button class="buttonDeletePhoto" onclick="DeletePhoto()"></button>
</div>
<a id="aLogo">
<img id="imgLogo" src="<%=path + "?time=" +System.currentTimeMillis()%>" width="100" height="100">
</a>
</div>
...
这是servlet,它将上传的文件复制到Alternate Document Root文件夹:
...
try
{
filePart = request.getPart("0");
String fullName = Common._FolderDatabase_LogoOrganization + File.separator + idOrganization + ".jpg";
File FileTemp = new File(fullName);
out = new FileOutputStream(FileTemp);
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
}
catch(IOException exception)
{
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Unable to copy file." + " Exception: ", exception);
response.sendError(HttpServletResponse.SC_ACCEPTED, "Unable to copy file.");
return;
}
finally
{
if (out != null)
out.close();
if (filecontent != null)
filecontent.close();
}
...
它工作正常,但有时(十分之一的尝试)浏览器无法下载图像源,并提供此错误:GET http://localhost:8080/GetSome/Database/LogoOrganization/85.jpg?time=1407933088377 404 (Not Found)
。我试图检查servlet是否有这样的文件:
File FileTemp = new File(fullName);
while(!FileTemp.canWrite())
{
Thread.sleep(1000);
}
并且像这样:
in = new FileInputStream(FileTemp);
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1)
{
}
在这两种情况下,该文件都可用,但它没有帮助。我猜Glassfish上传到文件夹后没有时间访问该文件。
答案 0 :(得分:0)
我通过检查Glassfish资源的可用性来解决问题
URL url = getServletContext().getResource(requestUri);
if (url != null) {
try
{
Thread.sleep(100);
}
catch (InterruptedException ex)
{
Logger.getLogger(UploadLogo.class.getName()).log(Level.SEVERE, null, ex);
}
}
感谢this answer。