【问题标题】:Display image in jsp page from servlet [duplicate]从servlet在jsp页面中显示图像[重复]
【发布时间】:2011-07-27 10:19:41
【问题描述】:

我的代码正在上传图像并将图像保存到我的服务器,但我需要在我的 jsp 页面中显示图像。

上传图片的jsp

uploadImage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head><title>Image Upload</title></head>

<body>
  <form action="UploadImage" method="post" enctype="multipart/form-data" 
           name="productForm" id="productForm"><br><br>
    <table width="400px" align="center" border=0 style="background-color:ffeeff;">
      <tr>
        <td align="center" colspan=2 style="font-weight:bold;font-size:20pt;">
           Image Details</td>
      </tr>

      <tr>
        <td align="center" colspan=2>&nbsp;</td>
      </tr>

      <tr>
        <td>Image Link: </td>
        <td>
          <input type="file" name="file" id="file">
        <td>
      </tr>

      <tr>
        <td></td>
        <td><input type="submit" name="Submit" value="Submit"></td>
      </tr>
      <tr>
        <td colspan="2">&nbsp;

        </td>
      </tr>

    </table>
  </form>
</body>

</html> 

小服务程序

上传图片

public class UploadImage extends HttpServlet {
    /**
     * 
     */

    private static final long serialVersionUID = 2082405235440894340L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        File filenameImg;
        List<FileItem> items = null;
        try {
            items = new ServletFileUpload(new DiskFileItemFactory())
                    .parseRequest(request);
        } catch (FileUploadException e) {
            throw new ServletException("Cannot parse multipart request.", e);
        }

        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form fields here the same way as
                // request.getParameter().
                // You can get parameter name by
                item.getFieldName();
                // You can get parameter value by item.getString();
            } else {

                try{
                    // Process uploaded fields here.
                    String filename = FilenameUtils.getName(item.getName());
                    // Get filename.
                    String path = GetWebApplicationPathServlet.getContext().getRealPath("/images");

                    File file =  new File(path,filename);


                    //File file = new File("C:\\", filename);

                    // Define destination file.

                    item.write(file);
                    System.out.println("filename: "+filename);
                    System.out.println("file: "+file);
                    request.setAttribute("image", file);
                    filenameImg = file;
                    // Write to destination file.
                //  request.setAttribute("image", filename);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        // Show result page.


        System.out.println("request"+request.getAttribute("image"));
        response.setContentType("image/jpeg"); 
        //request.getRequestDispatcher("result.jsp").forward(request, response);

        String nextJSP = "/result.jsp";
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher(nextJSP);
        dispatcher.forward(request, response);

    }

}

result.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%=request.getParameter("image")%>

<img src="<%=request.getParameter("image")%>">
</body>
</html>

在 result.jsp 页面中返回为 null

帮助

【问题讨论】:

  • 您能否告诉我们您是否愿意在预览之前将此图像存储在某个位置? ..会有所帮助,请回答
  • @Falcon 我需要将图像存储在我的 tomcar 服务器中。我在我的项目中创建了一个文件夹 images 并且图像被保存在该特定目录中,但我的问题是我无法在我的 jsp 页面中显示保存的图像
  • 你做得对。现在只需在请求中传递带有上传图像名称的路径。
  • 检查我的答案,在这种情况下第 1 点可能会有所帮助

标签: java jsp servlets


【解决方案1】:

&lt;img src="&lt;%=request.getParameter("image")%&gt;"&gt;

首先srcimg 标记只将图像路径作为字符串,因此您不能在其中传递整个图像。

现在您可以做的是:-- 当您在服务器上上传图片时,不要在请求中保存/传递整个图片文件,而只需在您上传图片的请求中添加图片的路径.在您的代码路径中是path + *file separator* + filename。将其传递给 img 标签的 src ,它就可以解决问题。这里文件分隔符可以是"/""\\"

希望这会有所帮助。


正如BalusC在评论中所建议最好使用&lt;img src="${param.image}" /&gt;

【讨论】:

  • 第二件事你错了。 HTML 和 JSP scriptlet 不同步运行之类的。
  • @BalusC:所以你的意思是说如果我们这样写它不会给出任何错误:&lt;img src="&lt;%=request.getParameter("image")%&gt;"&gt;
  • 正确。也许有问题的编辑器会这样做(通过警告或暗示性突出显示),但它在技术上完全没问题。自己试试。您可能对混合 HTML 和 JavaScript 感到困惑。由于它们都在客户端计算机上运行,​​因此引用很重要。
  • @BalusC:你是对的。谢谢。让我更新我的答案。
  • 以这种方式使用它不是更好。使用&lt;img src="${param.image}" /&gt; 会好很多。
【解决方案2】:

您采用的方法有两个错误。首先,在上面的 servlet 代码中,您已经像在下载图像文件一样进行编码(您已将内容类型设置为图像。

其次,您没有将图像文件关联到响应。不是通过图像参数或流。

现在,由于您混合了两种方法.. 您需要先决定您需要什么。根据您的解释,我了解到您正试图在 result.jpg 中显示上传的图像。在这种情况下,您不需要发送设置了内容类型的图像。在您的 result.jsp 中,img 标记需要显示图像的路径。因此,您需要将图像的路径设置为“图像”属性作为响应。

response.setAttribute("image", imagepath);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);

图片路径应该是访问图片的有效 URL。在你的 result.jsp 中你需要:

request.getParameter("image");

获取图像。它将是这样的:

<img src='<%=request.getParameter("image")%>'>

【讨论】:

  • 我已经按照你的建议做了,图像正在我的 Eclipse 浏览器中显示。但是当我在我的 IE 中使用应用程序时,图像没有显示在那里......请帮助
【解决方案3】:

在您的 servlet 中设置一个请求属性,该属性将您的图像的完整路径返回到 JSP。

String fullpath = path + File.separator + filename

request.setAttribute("fullpath",fullpath);

您已经将请求转发到 JSP。

所以,现在获取属性使用

<% 

String path = "";
if(request.getAttribute("fullpath")!=null)
    path = request.getAttribute("fullpath").toString();

%>

在您的 JSP 中,然后使用该路径显示图像

<img src='<%=path%>'>

【讨论】:

  • 完整路径是什么意思?如果图像存储在 'd' 驱动器上,那么完整路径将是 'd:\someImage.jpg'.. 这就是你的意思吗?如果是这样,那它就行不通了。
【解决方案4】:

我正在考虑您将图像文件存储在服务器上的某个位置 -

  1. 如果该路径在您的应用程序中,那么您可以直接在图像 src 属性中提供该路径,例如-
    如果您将文件存储在&lt;context root&gt;/resources/image/someImage.jpg 之类的地方,那么您可以提供该路径(路径应该在应用程序内部,可通过浏览器使用您的上下文 rrot 访问)图像 src 属性,浏览器将指向该图像。
  2. 您可以将文件存储在服务器中的某个位置(应用程序外部说“d:\someImage.jpg”)然后浏览器无法直接访问该文件,但您仍然可以通过 servlet 显示该图像,例如-
    您可以编写一个新的 servlet,并在 goGet 方法中读取图像文件并将其写入响应输出流。在图像的 src 中给出这个 servlet url,比如 -

例如

<image src="context root/displayServlet?image=someImage.jpg">


servlet 代码可能看起来像 -
编辑: - 要获得更好的代码,请参阅 How to retrieve and display images from a database in a JSP page?

try{
         String fileName = request.getParameter("image");             
         FileInputStream fis = new FileInputStream(new File("d:\\"+fileName));
         BufferedInputStream bis = new BufferedInputStream(fis);             
         response.setContentType(contentType);
         BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
         for (int data; (data = bis.read()) > -1;) {
           output.write(data);
         }             
      }
      catch(IOException e){

      }finally{
          // close the streams
      }

你可以改进这段代码,我只是举个例子。

【讨论】:

  • InputStream#available() 不返回文件内容长度。它甚至可能返回0
  • @BalusC - 感谢您指出这一点.. 有更好的替代方案吗?
  • 只需以通常的方式通过缓冲区循环写入。当文件内容大于可用的 Java 内存时,您不希望出现内存不足错误的风险。
  • 我遇到了类似的问题,你的回答很有帮助。
【解决方案5】:

Jeje,null的问题是因为是不同的东西;属性和参数,如果你这样做了:

request.setAttribute("image", file.getPath()); 

那么你需要做的:

request.getAttribute("image")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2012-09-29
    相关资源
    最近更新 更多