JSP中的图像上传和显示
我已经学习并成功实现了如何使用 servlet 从 这里现在尝试借助以下代码在另一个jsp userProfile.jsp
上显示图像:
<img src="<jsp:include page='WEB-INF/jspf/profileImage.jspf' />" height="175" width="175" />
profileImage.jspf
的代码是如下:
OutputStream o = response.getOutputStream();
InputStream is = new FileInputStream(new File("../files/backPetals.jpg"));
byte[] buf = new byte[32 * 1024];
int nRead = 0;
while( (nRead=is.read(buf)) != -1 ) {
o.write(buf, 0, nRead);
}
o.flush();
o.close();
return;
但它不起作用.. 还有其他方法可以在 jsp 上显示磁盘中的图像以及页面上的其他内容吗? 我已将图像保存在应用程序根文件夹的 /files
目录中。
I've learned and implement successfully that how to upload images on server disk with servlet from Here and now trying to show the image on another jsp userProfile.jsp
with the help of following code :
<img src="<jsp:include page='WEB-INF/jspf/profileImage.jspf' />" height="175" width="175" />
and code of profileImage.jspf
is as follows:
OutputStream o = response.getOutputStream();
InputStream is = new FileInputStream(new File("../files/backPetals.jpg"));
byte[] buf = new byte[32 * 1024];
int nRead = 0;
while( (nRead=is.read(buf)) != -1 ) {
o.write(buf, 0, nRead);
}
o.flush();
o.close();
return;
but it does not works..
Any other ways to display the image from disk on jsp together with other matter on page?
I've saved my images on /files
directories on the application root folder.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该方法存在几个严重错误:
您不应将上传的文件存储在应用程序根文件夹中。每当您重新部署 WAR 时,它们都会丢失(只是因为这些文件不包含在原始 WAR 文件中。
不应包含原始图像内容,但应包含返回该文件的 URL例如内容。
您不应该使用 JSP 将二进制数据写入响应。请改用 servlet。或者,如果可以的话,只需将上传文件的路径添加为另一个 web 应用程序上下文。
以下几个答案应该可以帮助您朝着正确的方向前进:
There are several serious mistakes in the approach:
You should not store the uploaded file in the application root folder. They will all get lost whenever you redeploy the WAR (simply because those files are not contained in the original WAR file.
The
<img src>
should not contain the raw image content, but it should contain an URL which returns the file content. E.g.You should not use JSP to write binary data to the response. Use a servlet instead. Or if you can, just add the path to uploaded files as another webapp context.
Here are several answers which should help you in the right direction:
img
标记的语法为。您正在做的是
。
您需要生成一个 servlet 的 URL,并且该 servlet 需要打开图像文件并将其内容发送到输出流。您无法在单个 HTTP 请求中下载 HTML 文件和图像。
The syntax of an
img
tag is<img src="url_of_the_image" .../>
. What you're doing is<img src="contents_of_the_image_file" .../>
.You need to generate a URL to a servlet, and this servlet needs to open the image file and send its content to the output stream. You can't download an HTML file and an image in a single HTTP request.