我对以下情况有点迷茫:
- 用户上传图片 - upload.jsp (multipart/form-data)
- servlet 完成所有脏活(保存图像、获取名称、保存名称、重定向到 display.jsp)
- 在 display.jsp 上,应该显示刚刚上传的图像
不幸的是 display.jsp 页面是空的。当我在 Firefox 下查看源页面时,一切似乎都很好,提供了指向图像的有效链接。
<img src="/UploadTest/avatar/55_445194458350473498.png" border=0 width="48px" height="48px"/>
但在媒体信息下,我可以看到一些奇怪的信息:
Location: http://localhost:8084/UploadTest/avatar/55_445194458350473498.png
Type: text/html
Size: Unknown (not cached)
Dimensions: 0px x 0px (scaled to 0px x 16px)
下面是用于上传、处理和显示图片的代码:
上传.jsp
<form action="Upload" method="post" enctype="multipart/form-data">
<label for="file">File:</label>
<input type="file" id="file" name="file">
<input type="submit" value="submit">
</form>
上传.java
(MultipartMap servlet 属于 BalusC,http: //balusc.blogspot.com.au/2009/12/uploading-files-in-servlet-30.html )
package test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import test.MultipartMap;
@WebServlet(urlPatterns = { "/Users/Thomas/NetBeansProjects/UploadTest/web/Upload" })
@MultipartConfig(location = "/Users/Thomas/NetBeansProjects/UploadTest/web/avatar", maxFileSize = 10485760L) // 10MB.
public class UploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
MultipartMap map = new MultipartMap(request, this);
File file = map.getFile("file");
String filename = file.getName();
HttpSession session = request.getSession();
session.setAttribute("filename", filename);
request.getRequestDispatcher("/display.jsp").forward(request, response);
}
}
显示.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div>
<img src="${pageContext.request.contextPath}/avatar/${filename}" border=0 width="48px" height="48px"/>
<div>
</body>
</html>
如果我在 display.jsp 中将 ${filename} 替换为之前上传的特定图像的静态名称,则显示没有问题,所以我认为图像已正确处理,只是前端缺少某些东西?
顺便说一句:当调试器处于活动状态时,一切正常,但当关闭时问题又回来了。
干杯,
托马斯