使用 JSP 将图像文件的内容转储到浏览器

发布于 2024-11-08 06:55:48 字数 448 浏览 0 评论 0原文

如何将磁盘上图像文件的内容转储到浏览器?

我尝试了此操作,但图像已损坏(浏览器中的图像符号已损坏)。

<%@ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

策马西风 2024-11-15 06:55:50

需要考虑两件事,
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

不打扰别人 2024-11-15 06:55:49

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 the doGet() 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:

甜味超标? 2024-11-15 06:55:49

有必要删除 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);
}

%>

It is neccessary to remove the line breaks outside of the JSP tags to not break the image.

<%@ 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);
}

%>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文