论坛首页 Java企业应用论坛

commons-fileupload-1.2.1文件上传

浏览 2490 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-05-13  
在servlet3.0之前,文件上传不是很好用,好多地方都需要自己实现。这个时代,我们都是依靠commons-fileupload-1.2.1来实现的。servlet3.0里面,不使用commons-fileupload-1.2.1也很容易实现。不过本文是在介绍commons-fileupload-1.2.1,所以不多说。直接看代码吧。

package com.panguso.phl.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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;

/**
 * 上传的测试代码
 * 
 * @author piaohailin
 * @date 2013-1-31
 */
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // 用于存放上传文件的目录
    private String            uploadPath       = "c:\\upload";
    private File              tempPath         = new File("c:\\upload\\temp");

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
    }

    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("UTF-8");

        // 创建一个上传项目工厂,并设置其缓存数据大小和临时文件保存位置
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        factory.setRepository(tempPath);

        // 使用项目工厂创建一个ServletFileUpload对象,用于解析文件上传请求
        // 并设置可以上传的文件的最大字节数,超过会抛出异常
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1024 * 1024);
        upload.setHeaderEncoding("utf-8");
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                System.out.println(fileItem.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics