使用 JSP 将图像文件的内容转储到浏览器
如何将磁盘上图像文件的内容转储到浏览器?
我尝试了此操作,但图像已损坏(浏览器中的图像符号已损坏)。
<%@ include file="config.jsp" %>
<%@ page import="java.io.*" %>
<%@ page contentType="image/png" %>
<%
String fn = request.getParameter("f");
String filename = uploads_folder + fn;
File file = new File(filename);
FileInputStream in = new FileInputStream(filename);
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
%>
How can I dump the contents of an image file on disk to the browser?
I tried this but the image is broken (broken image symbol in the browser).
<%@ include file="config.jsp" %>
<%@ page import="java.io.*" %>
<%@ page contentType="image/png" %>
<%
String fn = request.getParameter("f");
String filename = uploads_folder + fn;
File file = new File(filename);
FileInputStream in = new FileInputStream(filename);
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
%>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
需要考虑两件事,
1) 数据未因空格而损坏,使用“trimDirectiveWhitespaces”此页面指令属性来修剪空格。
2)设置图像内容类型标题
谢谢,
拉梅什
Two things to consider,
1) the data is not corrupt with whitespaces, use 'trimDirectiveWhitespaces' this page directive attribute to trim white spaces.
2) set the image content-type header
Thanks,
Ramesh
JSP 是 HTML/CSS/JS 和其他基于文本的内容的模板。它并不意味着作为图像等二进制数据的模板。从本质上讲,JSP 是不适合这项工作的工具。您应该使用 servlet 类。创建一个
扩展 HttpServlet
的类,并执行与 JSP 中的doGet()
方法完全相同的工作(尽管它可以变得更加健壮和高效)最后将图像 URL 更改为 servlet URL,而不是 JSP URL。另请参阅:
A JSP is meant as template for HTML/CSS/JS and other text based content. It's not meant as template for binary data like images. In essence, a JSP is the wrong tool for the job. You should be using a servlet class. Create a class which
extends HttpServlet
and do exactly the same job as you did in JSP in thedoGet()
method (although it can be made a bit more robust and efficient) and finally change the image URL to the servlet one instead of the JSP one.See also:
有必要删除 JSP 标记之外的换行符,以免破坏图像。
It is neccessary to remove the line breaks outside of the JSP tags to not break the image.