我正在尝试向我的网页添加一些简单的用户图片上传功能。目前,我(据我所知)上传了一张图片 - 当我上传图片时,它会显示在我的网络应用目录中的正确文件夹中。但是,我尝试在用户上传后在页面上显示图片,但出于某种原因它甚至不会出现,即使页面来源看起来正确......
在jsp文件中我使用代码
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () ) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
}
else {
file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + filePath + fileName + "<br></br>");
out.println("<img src = \"uploads/" + fileName + "\"></img>");
当我上传图片时,页面会显示&#34;已上传的文件名:...&#34;但不是图像。如果我查看页面源我还可以看到引用图像的代码行,如果我点击图像源&#34; uploads / photo.png&#34;,照片将在新的浏览器页面中打开。我不知道为什么我无法显示它 - 我也尝试改变路径,但似乎这应该是正确的...
我的文件夹结构是: web应用 根 的index.jsp upload.jsp 上传 photo.png
这是Tomcat(我使用的是Tomcat 7)还是我使用jsp页面或文件路径的问题?如果有人有任何线索,我将不胜感激......
答案 0 :(得分:0)
您对图片代码的语法不正确。 Img标签是自动关闭的(<img />
)而不是两个部分(<img></img>
)。
out.println("<img src='uploads/" + fileName + "' />");
我将\"
更改为'
,以便于阅读。 HTML可以使用单引号作为属性。
答案 1 :(得分:0)
通过将这两行添加到jsp:
生成的html文件的顶部来修复它out.println("<!DOCTYPE html>");
out.println("<html xmlns='http://www.w3.org/1999/xhtml'>");