gpt4 book ai didi

image - 通过 URI 中的文件名而不是请求参数来识别 servlet 中的图像请求

转载 作者:行者123 更新时间:2023-12-04 04:41:37 25 4
gpt4 key购买 nike

我使用 servlet 获取从我的项目中保存的图像。我的 servlet 中的代码是:

String file = request.getParameter("file"); 
BufferedInputStream in = new BufferedInputStream(new FileInputStream(directory + file));
// Get image contents.
byte[] bytes = new byte[in.available()];
in.read(bytes);
in.close();
// Write image contents to response.
response.getOutputStream().write(bytes);

HTML 图像标签是这样的:

<img src="/images/?file=example.jpg" />

一切都很好。但现在我想在 URI 中包含图像文件名,而不是像这样作为请求参数:

<img src="/images/example.jpg" />

我怎样才能实现它?

最佳答案

将 servlet 映射到前缀 URL 模式 /images/* 而不是明显精确的 URL 模式 /images。然后,您可以像这样指定 URL,并通过 HttpServletRequest#getPathInfo() 获取文件名作为 URI 路径信息。 .

启动示例:

@WebServlet("/images/*")
public class ImageServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getPathInfo().substring(1);
File file = new File(directory, filename);
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", String.valueOf(file.length()));
Files.copy(file.toPath(), response.getOutputStream());
}

}

具体问题无关:InputStream#available()因为在你的初始代码中没有做你显然认为它做的事情。它不会返回内容的整个长度。它只返回代码可以读取的第一个 block 的长度,而不会阻塞磁盘文件系统 I/O。 IE。它返回 I/O 缓冲区中当前内容的长度。这不一定代表整个内容长度!肯定不会在较大的图像上。如果您使用的是 Java 7,只需使用 Files#copy()如果唯一的目的是用尽可能少的代码完成工作,如上所示。

关于image - 通过 URI 中的文件名而不是请求参数来识别 servlet 中的图像请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18788079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com