日期:2014-05-16  浏览次数:20469 次

JSP文件上传组件

JSP上传组件整理

第1个上传组件commons-fileupload

=============commons-fileupload ================

common-fileupload组件是apache的一个开源项目之一,可以从http://jakarta.apache.org/commons/fileupload/下载。该组件简单易用,可实现一次上传一个或多个文件,并可限制文件大小。

-下载后解压zip包,将commons-fileupload-1.1.1.jar,和commons-io-1.2.jar复制到tomcat的webapps\你的webapp\WEB-INF\lib\下,如果目录不存在请自建目录。

新建一个servlet: FileUpload.java用于文件上传:

package com.drp.util.servlet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.*;

import java.util.*;

import java.util.regex.*;

import java.io.*;

import org.apache.commons.fileupload.servlet.*;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

public class FileUpload extends HttpServlet {

?private String uploadPath = ""; // 用于存放上传文件的目录

?

?private File tempPath = new File("D:\\Tomcat 5.5\\webapps\\drp1.2\\tempimages\\"); // 用于存放临时文件的目录

?public void doPost(HttpServletRequest req, HttpServletResponse res)

?? throws ServletException, IOException {

? res.setContentType("text/html; charset=GB18030");

? PrintWriter out = res.getWriter();

? System.out.println(req.getContentLength());

? System.out.println(req.getContentType());

? DiskFileItemFactory factory = new DiskFileItemFactory();

? // maximum size that will be stored in memory

? //允许设置内存中存储数据的门限,单位:字节

? factory.setSizeThreshold(4096);

? // the location for saving data that is larger than getSizeThreshold()

<