Java Servlet图片上传至指定文件夹并显示图片

在学习Servlet过程中,针对图片上传做了一个Demo,实现的功能是:在a页面上传图片,点击提交后,将图片保存到服务器指定路径(D:/image);跳转到b页面,b页面读取展示绝对路径(D:/image)的图片。主要步骤如下:

步骤一:上传页面uploadphoto.jsp

  需要注意两个问题:

  1.form 的method必须是post的,get不能上传文件, 还需要加上enctype="multipart/form-data" 表示提交的数据是二进制文件。

  2.需要提供type="file" 的字段进行上传     

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>upload page</title>
</head>
<body >
    <form action="uploadPhoto" method="post" enctype="multipart/form-data">
          英雄名称: <input type="text" name="heroName" /> <br><br> 
          上传头像: <input type="file" name="filepath" /> <br><br> 
                   <input type="submit" value="上传">
    </form>
</body>
</html>

步骤二:UploadPhotoServlet类

  1. 需要用到两个第三方的jar包,commons-io-1.4.jar和commons-fileupload-1.2.2.jar。项目是Maven项目,直接在pom.xml文件中引入:

<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
</dependency>
<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
</dependency>

   2. 前部分代码是固定写法,用来做一些准备工作。 直到遍历出Item,一个Item就是对应一个浏览器提交的数据,通过item.getInputStream可以打开浏览器上传的文件的输入流。
    3. 客户提交的文件名有可能是一样的,所以在服务端保存文件的时候,不能使用客户提交的文件名。这里使用的是一种粗糙的解决文件名重复的办法,即使用时间戳。

package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadPhotoServlet extends HttpServlet {
    public static String filename = null;
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest request,HttpServletResponse response){
        
    }

    @SuppressWarnings("rawtypes")
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        
        factory.setSizeThreshold(1024 * 1024);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        
        Iterator iter = items.iterator();
        while(iter.hasNext()){
            FileItem item = (FileItem) iter.next();
            if(!item.isFormField()){
                
                // 根据时间戳创建头像文件
                filename = System.currentTimeMillis() + ".jpg";
                System.out.println(request.getContextPath());
                /*File f = new File(getServletContext().getRealPath("upload"));*/
                File f = new File("D://image");
                if (!f.exists()) {  
                    f.mkdir();  
                } 
                String imgsrc = f + "/" + filename;
                
                // 复制文件
                InputStream is = item.getInputStream();               
                FileOutputStream fos = new FileOutputStream(imgsrc);
                byte b[] = new byte[1024 * 1024];
                int length = 0;
                while (-1 != (length = is.read(b))) {
                    fos.write(b, 0, length);                    
                }
                fos.flush();
                fos.close();  
                
            }else {
                System.out.println(item.getFieldName());
                String value = item.getString();
                value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
                System.out.println(value);
            }
        }         
        //request.setAttribute("filename", filename);      
        //request.getRequestDispatcher("/showPhoto").forward(request, response);
        response.sendRedirect("/ServletTest/showPhoto?filename="+filename);      
    }
}

步骤三:ShowPhotoServlet类

  其实这个类可以省略,即可以直接在UploadPhotoServlet类中跳转到页面showphoto.jsp,但是为了学习Servlet跳转方面的知识,于是增加一个新的Servlet类。

package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShowPhotoServlet extends HttpServlet{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        String filename = request.getParameter("filename").toString();
        response.sendRedirect("/ServletTest/showphoto.jsp?filename="+filename);    
    }
    
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        String filename = request.getAttribute("filename").toString();
        request.setAttribute("filename", filename);
        request.getRequestDispatcher("/showphoto.jsp").forward(request, response);
    }
}

  1.servlet跳转至jsp

     详见:http://blog.csdn.net/yoxibaga/article/details/8624056

   a.服务端跳转浏览器的地址不变(请求转发)

   request.setAttribute("filename", filename);

   request.getRequestDispatcher("/showphoto.jsp").forward(request, response); 

   b.客户端跳转浏览器的地址发生变化(请求重定向)

   response.sendRedirect("/ServletTest/showphoto.jsp?filename="+filename);    

  2.servlet跳转至另一个servlet 

   a.服务端跳转需要重写doPost以获取传递参数       

   String filename = request.getAttribute("filename").toString();

   b.客户端跳转需要重写doGet以获取传递参数  

   String filename = request.getParameter("filename").toString();

步骤三:web.xml配置

    <servlet>
        <servlet-name>UploadPhotoServlet</servlet-name>
        <servlet-class>servlet.UploadPhotoServlet</servlet-class>
    </servlet> 
    <servlet-mapping>
        <servlet-name>UploadPhotoServlet</servlet-name>
        <url-pattern>/uploadPhoto</url-pattern>
    </servlet-mapping>  
    
    <servlet>
        <servlet-name>ShowPhotoServlet</servlet-name>
        <servlet-class>servlet.ShowPhotoServlet</servlet-class>
    </servlet> 
    <servlet-mapping>
        <servlet-name>ShowPhotoServlet</servlet-name>
        <url-pattern>/showPhoto</url-pattern>
    </servlet-mapping> 

步骤四:展示页面showphoto.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Image page</title>
</head>
<body>
<%
    String filename = request.getParameter("filename"); 
    String srcimg = "/image/"+filename;
%>
<img src="<%=srcimg%>"/>
</body>
</html>

  1.配置虚拟路径

  图片和工程不在一个盘符下。图片也不能放到工程下。 在JSP 文件中 <img src="C:/Users/fx/Pictures/test.jpg"/>  这样是引不到图片的。因为,JSP页面在引图片的时候是在页面解析的路径是:<img src="http://localhost:8080/test/images/1.jpg">。也就是说JSP在引图片的时候是先去工程目录下找的。

  解决办法:

  使用虚拟路径来配置,在tomcat下的server.xml中增加一个代码 在<Host></Host>中间: 

  <Context docBase="D:\image" path="/image" reloadable="true"/>

   然后在JSP页面中<img src = "/image/(图片名)">就可以访问图片了。

 

最终实现效果:

上传界面:

 

 展示界面:                                 

                                                    

 保存图片的文件夹:

                                

 

posted @ 2017-08-03 13:55  Junsept  阅读(5552)  评论(0编辑  收藏  举报