Servlet上传文件,commons-fileupload

<form name="uploadForm" method="POST" enctype="MULTIPART/FORM-DATA"
    action="upload">

HTTP请求正文采用"multipart/from-data"数据类型,它表示复杂的包括多个子部分的复杂表单.

不管HTTP请求正文为何种数据类型,Servlet容器都会把HTTP请求包装成一个HTTPServletRequest对象.

Servlet直接从HTTPServletRequest对象中解析出复合表单的每个子部分仍然是一项非常复杂的工作.

因此可以利用Apache提供的两个软件包来实现文件上传.

commons-fileipload-1.2.1.jar

commons-io-1.4.jar

UploadServlet.java

package mypack;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
public class UploadServlet extends HttpServlet {
private String filePath;//存放上传文件的目录
private String tempFilePath;//存放临时文件的目录

public void init(ServletConfig config) throws ServletException {
   super.init(config);
   filePath = config.getInitParameter("filePath");
   System.out.println("filePath1 " + filePath);
   tempFilePath = config.getInitParameter("tempFilePath");
   System.out.println("tempFilePath1 " + tempFilePath);
   filePath = this.getServletContext().getRealPath(filePath);
   System.out.println("filePath2 " + filePath);
   tempFilePath = this.getServletContext().getRealPath(tempFilePath);
   System.out.println("tempFilePath2 " + tempFilePath);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

   response.setContentType("text/plain");
   //向客户端发送响应正文
   PrintWriter outNet = response.getWriter();

   try {
    //创建一个基于硬盘的FileItem工厂
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //设置向硬盘写数据时所用的缓冲区的大小,此处为4K
    factory.setSizeThreshold(4*1024);
    //设置临时目录
    factory.setRepository(new File(tempFilePath));

    //创建一个文件上传处理器
    ServletFileUpload upload = new ServletFileUpload(factory);
    //设置允许上传的文件的最大尺寸,此处为4M
    upload.setSizeMax(4*1024*1024);

    List items = upload.parseRequest(request);

    Iterator iter = items.iterator();

    while(iter.hasNext()) {
     FileItem item = (FileItem)iter.next();
     if(item.isFormField()) {
      processFormField(item,outNet); //处理普通的表单域
     } else {
      processUploadedFile(item,outNet); //处理上传文件
     }
    }   
    outNet.close();
   } catch (Exception ex) {
    ex.printStackTrace();
   }
}

private void processFormField(FileItem item, PrintWriter outNet) {
   String name = item.getFieldName();
   String value = item.getString();
   outNet.println(name + ":" + value + "\r\n");
}

private void processUploadedFile(FileItem item, PrintWriter outNet) throws Exception {
   String filename = item.getName();
   int index = filename.lastIndexOf("\\");
   filename = filename.substring(index+1, filename.length());
   long fileSize = item.getSize();

   if(filename.equals("") && fileSize == 0)
    return;

   File uploadFile = new File(filePath + "/" + filename);
   item.write(uploadFile);
   outNet.println(filename + "is saved.");
   outNet.println("The size of " +filename+" is "+fileSize+"\r\n");
   
   outNet.flush();

outNet.close();
 }}web.xml<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>UploadServlet</servlet-name> <servlet-class>mypack.UploadServlet</servlet-class> <init-param> <param-name>filePath</param-name> <param-value>store</param-value> </init-param> <init-param> <param-name>tempFilePath</param-name> <param-value>temp</param-value> </init-param></servlet><servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/upload</url-pattern></servlet-mapping>upload.htm<html><head> <title>Upload</title></head><body> <form name="uploadForm" method="POST" enctype="MULTIPART/FORM-DATA" action="upload"> <table> <tr> <td> <div align="right"> User Name: </div> </td> <td> <input type="text" name="username" size="30" /> </td> </tr> <tr> <td> <div align="right"> Upload File1: </div> </td> <td> <input type="file" name="file1" size="30" /> </td> </tr> <tr> <td> <div align="right"> Upload File2: </div> </td> <td> <input type="file" name="file2" size="30" /> </td> </tr> <tr> <td> <input type="submit" name="submit" value="upload"> </td> <td> <input type="reset" name="reset" value="reset"> </td> </tr> </table> </form></body></html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值