• Servlet上传文件


    Servlet上传文件


    1、准备工作

    (1)利用FileUpload组件上传文件,须要到apache上下载commons-fileupload-1.3.1.jar

             下载地址:http://commons.apache.org/fileupload/

    (2)因为文件上传还得有IO流传输,须要到apache上下载commons-io-2.4.jar

             下载地址:http://commons.apache.org/io/


    2、正式开发

    (1)新建文件上传界面

            file.jsp:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%  
    String path = request.getContextPath();  
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
    %> 
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>"> 
        
        <title>上传文件前</title>
        
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    	
    
      </head>
      
      <body>
        <form action="FileUploadServlet" method="post" enctype="multipart/form-data">
            <table>
               <tr>
                 <td>
                    <label for="username">用户名:</label>
                	<input type="text" name="username"/>
                 </td>
               </tr>
               <tr>
                 <td>
                   <label for="password">密  码:</label>
               	   <input type="password" name="password"/>
                 </td>
               </tr>
               <tr>
                 <td>
                           
                   <input type="file" name="fileOne" id="fileOne"/>
                 </td>
               </tr>
               <tr>
                 <td>
                           
                   <input type="file" name="fileTwo" id="fileTwo"/>
                 </td>
               </tr>
               <tr>
                  <td>
                            
                    <input type="submit" name="submit" id="submit" value="提交"/>
                         
                    <input type="reset" name="reset" id="reset" value="重置"/>
                  </td>
               </tr>
            </table>
        </form>
      </body>
    </html>
    

    (2)新建文件上传成功界面

             result.jsp:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%  
    String path = request.getContextPath();  
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
    %> 
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>"> 
        <title>上传文件成功</title>
        
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    	
    
      </head>
      
      <body>
             用户名:<%= request.getAttribute("username") %><br/>  
    	密  码:<%= request.getAttribute("password") %><br/>  
    	文件一:<%= request.getAttribute("fileOne") %><br/>  
    	文件二:<%= request.getAttribute("fileTwo") %><br/>  
      </body>
    </html>
    

    (3)新建servlet进行文件上传处理

            FileUploadServlet.java:

    package com.you.file.servlet;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    public class FileUploadServlet extends HttpServlet 
    {
    	/**
    	 * @Fields  serialVersionUID:
    	 */
    	private static final long serialVersionUID = -3788743064732005240L;
    	
    	/**
    	 * The doPost method of the servlet. <br>
    	 *
    	 * This method is called when a form has its tag value method equals to post.
    	 * 
    	 * @param request the request send by the client to the server
    	 * @param response the response send by the server to the client
    	 * @throws ServletException if an error occurred
    	 * @throws IOException if an error occurred
    	 */
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException 
    	{
    		/**
    		 * 设置编码格式
    		 */
    		request.setCharacterEncoding("UTF-8");
    		/**
    		 * 创建一个工厂类
    		 */
    		DiskFileItemFactory factory = new DiskFileItemFactory();
    		ServletContext context = getServletContext();  
    		String path = context.getRealPath("/file");
    		/**
    		 * 设置上传文件放在磁盘上的暂时文件夹
    		 */
    		factory.setRepository(new File(path));
    		/**
    		 * 设置上传文件大小
    		 */
    		factory.setSizeThreshold(1024*1024);
    		
    		//上传对象
    		ServletFileUpload fileuplod = new ServletFileUpload(factory);
    		try 
    		{
    			/**
    			 * 解析各个表单域
    			 */
    			List<FileItem> list = fileuplod.parseRequest(request);
    			
    			for(FileItem item : list)
    			{
    				/**
    				 * 推断是简单域 (item.isFormField()==true)
    				 */
    				if(item.isFormField())
    				{
    					//获得简单域的名字
    					String fieldName = item.getFieldName();
    					//获得简单域的值
    					String fieldValue = item.getString("UTF-8");
    					request.setAttribute(fieldName, fieldValue);
    				}
    				else//推断是文件域 (item.isFormField()==false)
    				{
    					//获得文件域的名字
    					String fieldName = item.getFieldName();
    					//获得文件域的值,带路径,即是路径+文件名称
    					String value = item.getName();
    					//取的文件域的值的名字,不带路径
    					int temp = value.lastIndexOf("\");
    					String fieldValue = value.substring(temp+1);
    					//获得是file文件的内容
    					request.setAttribute(fieldName, fieldValue);
    					
    					//写入
    					item.write(new File(path,fieldValue));
    				}
    			}
    		} 
    		catch (Exception e) 
    		{
    			//e.printStackTrace();
    		}
    		/**
    		 * 跳转到上传成功界面
    		 */
    		request.getRequestDispatcher("result.jsp").forward(request, response);
    	}
    	
    	/**
    	 * Initialization of the servlet. <br>
    	 * init方法
    	 * @throws ServletException if an error occurs
    	 */
    	public void init() throws ServletException 
    	{
    		
    	}
    	
    	/**
    	 * destroy方法
    	 * Destruction of the servlet. <br>
    	 */
    	public void destroy() 
    	{
    		super.destroy(); 
    	}
    	
    	/**
    	 * The doGet method of the servlet. <br>
    	 *
    	 * This method is called when a form has its tag value method equals to get.
    	 * doGet方法
    	 * @param request the request send by the client to the server
    	 * @param response the response send by the server to the client
    	 * @throws ServletException if an error occurred
    	 * @throws IOException if an error occurred
    	 */
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException 
    	{
    		this.doPost(request, response);
    	}
    }
    

    (3)配置web.xml

    <?

    xml version="1.0" encoding="UTF-8"?

    > <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>FileUploadServlet</servlet-name> <servlet-class>com.you.file.servlet.FileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileUploadServlet</servlet-name> <url-pattern>/FileUploadServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>


    3、过程演示

    (1)初始化时



    (2)输入username、password,上传文件



    (3)还未上传。项目中的file目录



    (4)上传成功后,页面显示



    (5)上传成功后,file目录


    版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 相关阅读:
    LAMP应用 wdlinux 配置文件
    Linux mysql忘记root密码
    vim 编辑器 常用的设置
    Virtual PC(VPC)虚拟机安装CentOS 6.0网络配置
    缓存系统memcache的安装,配置和使用
    CentOS 去掉Last login提示/系统欢迎信息
    configure: error: GD build test failed. Please check the config.log for details.
    Centos 6.0 yum 更新源
    MySQL is running but PID file is not found
    Visual Studio快速开发以及Visual Studio 2010新功能介绍
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4802864.html
Copyright © 2020-2023  润新知