只有web
(WEB-INF 和 META-INF 除外)文件夹的内容可以通过 url 公开访问,因此您上传的图像必须位于web
其中或其子文件夹中。
如果您将图像存储在另一个目录中,那么您将必须创建一个扩展的类HttpServlet
并将其映射到一个 URL,例如/myapp/uploads/*
(/myapp
是 ContextPath)每当访问该 url 时,例如/myapp/uploads/119.jpg
使用方法获取文件名request.getPathInfo()
并执行所需的验证(文件存在、权限等),然后读取文件并通过HttpServletResponse
的输出流提供它。
或者,如果不需要权限验证,您可以将 tomcats Default Servlet映射到url 模式。/uploads/*
您的图像标签的来源是<img src="/myapp/uploads/119.jpg" alt="Image" />
这是一个示例 servlet:
package servlets;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class StreamServlet extends HttpServlet {
private static final String WINDOWS_UPLOAD_DIR = "C:\\Projects\\Data\\img";
/**
* Serve the images from the specified dir.
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String fileName = req.getPathInfo().substring(1);
File imageFile = new File(WINDOWS_UPLOAD_DIR, fileName);
OutputStream os = resp.getOutputStream();
InputStream is = new FileInputStream(imageFile);
IOBridge(is, os);
os.flush();
Close(is, os);
}
/**
* Bridge data between an input and output stream.
*
* @param in The input stream.
* @param out The output stream
* @throws IOException if there's an error.
*/
private static void IOBridge(InputStream in, OutputStream out)
throws IOException {
byte data[] = new byte[1024];
int readCount = 0;
while ((readCount = in.read(data, 0, readCount)) != -1) {
out.write(data);
}
}
/**
* Close some closeables
*
* @param closeables The closeables to be closed.
*/
private static void Close(Closeable... closeables) {
for (Closeable c : closeables)
if (c != null)
try {
c.close();
} catch (IOException ioe) {
try {
c.close();
} catch (Exception e) {
e.printStackTrace();
}
} finally {
try {
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
然后在你的web.xml
,你会添加:
<servlet>
<servlet-name>StreamServlet</servlet-name>
<servlet-class>servlets.StreamServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StreamServlet</servlet-name>
<url-pattern>/uploads/*</url-pattern>
</servlet-mapping>
Java Servlet 规范 3.0