在servlet的jsp页面中显示图像 [英] Display image in jsp page from servlet

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

问题描述

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

My code is uploading an image and saving the image to my server, but I need to display the image in my jsp page.

用于上传图片的jsp

The jsp for uploading image

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> 

Servlet

UploadImage

UploadImage

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

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>

<%= request.getParameter("image")%> 在result.jsp页面中返回为空

<%=request.getParameter("image")%> is returned as null in the result.jsp page

帮助

推荐答案

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

I'm considering you are storing a image file somewhere on the server -

  1. 如果该路径位于您的应用程序内部,则可以直接在image src属性中指定该路径,例如-
    如果您将文件存储在<context root>/resources/image/someImage.jpg之类的位置,则可以指定该路径(路径应位于应用程序内部,可以使用上下文rrot通过浏览器访问)image src属性,浏览器将指向该图像.
  2. 您可以将文件存储在服务器中的某个位置(在应用程序外部说"d:\ someImage.jpg"),然后浏览器无法直接访问该文件,但仍然可以通过servlet显示该图像,例如-
    您可以编写一个新的servlet,并在goGet方法中可以读取图像文件并将其写入响应输出流.在图像的src中提供该servlet网址,例如-
  1. If that path is inside your application then you can give that path directly in the image src attribute, e.g. -
    if you're storing file somewhere like <context root>/resources/image/someImage.jpg then you can give that path (path should be inside the application which is accessible via browser with your context rrot) image src attribute and browser will point to that image.
  2. You can store the file somewhere in the server (outside of the application say "d:\someImage.jpg") then this cannot be reachable by the browser directly but you can still show that image via servlet, e.g. -
    you can write a new servlet and in the goGet method you can read the image file and write it to the response output stream. give this servlet url in the src of the image like -

例如

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


Servlet代码可能类似于-
-有关更好的代码,请参考如何检索和在JSP页面中显示数据库中的图像?


The servlet code may look like -
- For better code refer 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
      }

您可以改进此代码,我仅举一个例子.

You can improve this code, I'm just giving an example.

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

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