用commons FileUpload实现文件上传

1、到www.apache.org下载相关jar文件
2、创建一个web project,将相关包引入
(1)web.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">

	<servlet>
		<servlet-name>UploadFileServlet</servlet-name>
		<servlet-class>com.fileupload.servlet.UploadFileServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>UploadFileServlet</servlet-name>
		<url-pattern>/UploadFileServlet/*</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

(2)index.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>My JSP 'index.jsp' starting page</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">
		<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
	    function getUpFiles(){
	        var desc = document.getElementById("desc").value;
	        alert(desc);
	    }
	</script>
	</head>

	<body>
	<%
	   String fileName = "";
	   if(request.getAttribute("fileName")!=null){
	       fileName = (String)request.getAttribute("fileName");
	       out.println(fileName+"上传成功!");
	   }
	 %>
		<form method="post" action="UploadFileServlet" name="upForm"
		enctype="multipart/form-data" onsubmit="return getUpFiles();">
			<table width="100%" border="0">
				<tbody>
					<tr>
						<td width="15%">
							文件路径:
						</td>
						<td width="85%">
							<input type="file" name="upFile" size="30px"/>
						</td>
					</tr>
					<tr>
						<td width="15%">
							文件描述:
						</td>
						<td width="85%"> 
							<textarea name="desc" rows="10" cols="50"></textarea>
						</td>
					</tr>
					<tr>
						<td>
							&nbsp;
						</td>
						<td>
							<input type="Submit" name="upBotton" value="上传"/>
						</td>
					</tr>
					<tr>
						<td>
							&nbsp;
						</td>
						<td>
							&nbsp;
						</td>
					</tr>
				</tbody>
			</table>
		</form>
	</body>
</html>


(3)UploadFileServlet 类的实现
package com.fileupload.servlet;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
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 UploadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 56890894234786L;
	String saveFolder = "falshFolder";
	String saveTempFolder = "falshTempFolder";

    @SuppressWarnings("unchecked")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, java.io.IOException {
        request.setCharacterEncoding("UTF-8");

        // 文件上傳部分
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        
        if (isMultipart == true) {
            try {
            	// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
            	DiskFileItemFactory factory = new DiskFileItemFactory();
            	// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
            	factory.setSizeThreshold(4096);
            	//设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录
            	factory.setRepository(new File(request.getRealPath("/")+
            			saveTempFolder));
            	// 用配置好的工厂实例化上传组件
                ServletFileUpload upload = new ServletFileUpload(factory);
                
                // 得到所有的表单域,它们目前都被当作FileItem
                List<FileItem> fileItems = upload.parseRequest(request);
                Iterator<FileItem> iter = fileItems.iterator();
                
                // 依次处理每个表单域
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    
                    if(item.isFormField()){
                        // 如果item是正常的表单域
                        String name = item.getFieldName();
                        String value = item.getString();
                        System.out.print("表单域名为:"+name+"表单域值为:"+value);
                    }
                    else{
                        // 如果item是文件上传表单域
                        
                        // 获得文件名及路径
                        String fileName = item.getName();
                        if (fileName != null) {
                        	//获取要上传的文件
                            File fullFile = new File(item.getName());   
                            String t_ext = fullFile.getName().substring(fullFile.getName().lastIndexOf(".") + 1);

                            // 如果文件存在则上传
                            if(fullFile.exists()){
                            	//存放文件的路径
                                String filePath = request.getRealPath("/") + saveFolder;
                                long now = System.currentTimeMillis();
                                // 根据系统时间生成上传后保存的文件名
                                String name = String.valueOf(now);
                                File fileOnServer = new File(filePath,
                                        name+"."+t_ext);
                                item.write(fileOnServer);
                                
                                System.out.println("文件"+fileOnServer.getName()+"上传成功");
                                request.setAttribute("fileName", fullFile.getName());
                            }
                        }
                    }
                }                
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("the enctype must be multipart/form-data");
        }
        

        // 返回原页
        RequestDispatcher dispatcher = request
                .getRequestDispatcher("index.jsp");
        dispatcher.forward(request, response);
        return;
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, java.io.IOException {
        doPost(request, response);
    }

}


你可能感兴趣的:(java,apache,jsp,servlet,ext)