FileUpload

以下为apache fileupload的使用。

先一个servlet:

package servlet;

import java.io.File;
import java.io.IOException;
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 javax.swing.filechooser.FileNameExtensionFilter;

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


public class Upload extends HttpServlet {

	public void init() throws ServletException {
		System.out.println("servlet-upload init!");
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			request.setCharacterEncoding("GBK");
			String path = "d:\\111";
			System.out.println("path > "+path);
			boolean flag = ServletFileUpload.isMultipartContent(request);  
			if (flag==true) {
				try {
					FileItemFactory factory = new DiskFileItemFactory();
					ServletFileUpload upload = new ServletFileUpload(factory);
					//可以设置最大文件长度
					//upload.setSizeMax(1024000);
					List<FileItem> fileItems = upload.parseRequest(request);
					Iterator<FileItem> iterator = fileItems.iterator();
					//以下遍历所有post上来的表单域
					while (iterator.hasNext()) {
						FileItem item = iterator.next();
						if(item!=null){
							if(item.isFormField()){
								String name = item.getFieldName();
								System.out.println("name : "+name);
							}else {
								String filename = item.getName();
								if(filename!=null){
									File file = new File(item.getName());
									if(!file.exists()){
										item.write(new File(path,file.getName()));
										System.out.println("success!");
									}
								}
							}
						}
					}
				} catch (FileUploadException e) {
					System.out.println("异常了。。");
					e.printStackTrace();
				} catch (Exception ae) {
					System.out.println("异常了。。");
					ae.printStackTrace();
				}
			}else {
				System.out.println("caonima");
			}
			//得到已经上传的文件
			List<String> fileOnDisk = new ArrayList<String>();
			File filePath = new File(path);
			String fileName[] = filePath.list();
			if(fileName!=null){
				for(String str : fileName){
					fileOnDisk.add(str);
				}
				request.setAttribute("fileOnDisk", fileOnDisk);
			}
			RequestDispatcher rd = request.getRequestDispatcher("/TestUpload.jsp");
			rd.forward(request, response);
	}

	public void destroy() {
		System.out.println("servlet-upload destroyed!");
	}

}

 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>
    <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>Upload</servlet-name>
    <servlet-class>servlet.Upload</servlet-class>
  </servlet>



  <servlet-mapping>
    <servlet-name>Upload</servlet-name>
    <url-pattern>/servlet/Upload</url-pattern>
  </servlet-mapping>

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

 然后是测试页面:

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
	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>Test FileUpLoad!</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="<%=request.getContextPath()%>/servlet/Upload"
		method="post" enctype="multipart/form-data">
		<input type="file" name="uploadFile" value="浏览" /> <input
			type="submit" name="submit" value="submit" />
	</form>
	<%
		List list = (ArrayList)request.getAttribute("fileOnDisk");
		if (list != null) {
			out.println("***********************************<p>");
			for(int i=0;i<list.size();i++){
				out.println(list.get(i)+"<p>");
			}
			out.println("***********************************<p>");
		}
	%>
</body>


</html>
 收工。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值