JSP中的图像上传和显示 [英] Image Upload and Display in JSP

查看:164
本文介绍了JSP中的图像上传和显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已成功学习并实现了如何使用来自这里现在尝试使用以下代码在另一个jsp userProfile.jsp 上显示图像:

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" /> 

的代码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 目录中。

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.

推荐答案

该方法存在以下几个严重错误:

There are several serious mistakes in the approach:


  1. 您不应将上传的文件存储在应用程序根文件夹。重新部署WAR时,它们都会丢失(只是因为这些文件不包含在原始WAR文件中。

  1. 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.

< ; img src> 不应包含原始图片内容,但应包含返回文件内容的网址。例如

The <img src> should not contain the raw image content, but it should contain an URL which returns the file content. E.g.

<img src="profilePictures/${user.profilePictureFilename}" />


  • 您不应该使用JSP将二进制数据写入响应。请改用servlet。或者如果可以,只需将上传文件的路径添加为另一个webapp上下文。

  • 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:

    • How to provide relative path in File class to upload any file?
    • What is the correct path I need to see my uploaded image?
    • How I save and retrieve an image on my server in a java webapp

    这篇关于JSP中的图像上传和显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆