欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用fileupload包进行文件上传

程序员文章站 2022-07-13 22:45:58
...
  • 文件上传的必要前提:
    1. 提供form表单,method必须是post
    2. form表单的enctype必须是multipart/form-data(默认是application/x-www-form-urlencoded)
    3. 提供input type="file"类的上传输入域
  • 下面是实现文件上传的示例代码:
  • 需要导入的包如下:
WEB-INF/lib/commons-fileupload-1.2.2.jar
WEB-INF/lib/commons-io-2.2.jar
package Upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

public class UploadServlet extends HttpServlet {

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

        // 要执行文件上传的操作
        // 判断表单是否支持文件上传。即:enctype="multipart/form-data"
        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
        if (!isMultipartContent) {
            throw new RuntimeException("your form is not multipart/form-data");
        }

        // 创建一个DiskFileItemfactory工厂类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(new File("d:\\"));// 指定临时文件的存储目录
        // 创建一个ServletFileUpload核心对象
        ServletFileUpload sfu = new ServletFileUpload(factory);
        // 解决上传文件名乱码问题
        sfu.setHeaderEncoding("UTF-8");

        // 解析request对象,并得到一个表单项的集合
        try {
            List<FileItem> fileItems = sfu.parseRequest(request);

            // 遍历表单项数据
            for (FileItem fileitem : fileItems) {
                if (fileitem.isFormField()) {
                    // 普通表单项
                    processFormField(fileitem);
                } else {
                    // 上传表单项
                    processUploadField(fileitem);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }

    // 上传表单项
    private void processUploadField(FileItem fileitem) {
        try {
            // 得到文件输入流
            InputStream is = fileitem.getInputStream();

            // 创建一个文件存盘的目录
            String directoryRealPath = this.getServletContext().getRealPath("/WEB-INF/upload");
            File storeDirectory = new File(directoryRealPath);
            if (!storeDirectory.exists()) {
                storeDirectory.mkdirs();// 创建一个指定的目录
            }
            // 得到上传的文件名称
            String filename = fileitem.getName();
            //下面的操作只是为了防止上面的上传文件名包含路径名
            if (filename != null) {
                filename = FilenameUtils.getName(filename);
            }

            // 解决文件同名的问题
            filename = UUID.randomUUID() + "_" + filename;

            // 目录打散
            String childDirectory = makeChildDirectory(storeDirectory, filename);

            // 在storeDirectory下,创建完整目录下的文件
            File file = new File(storeDirectory, childDirectory + File.separator + filename); // 绝对目录/生成的子目录/文件名
            // 通过文件输出流将上传的文件保存到磁盘
            FileOutputStream fos = new FileOutputStream(file);

            int len = 0;
            byte[] b = new byte[1024];
            while ((len = is.read(b)) != -1) {
                fos.write(b, 0, len);
            }
            fos.close();
            is.close();
            //删除临时文件
            fileitem.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 目录打散
    private String makeChildDirectory(File storeDirectory, String filename) {
        int hashcode = filename.hashCode();// 返回字符转换的32位hashcode码
        System.out.println(hashcode);//1417749484
        String code = Integer.toHexString(hashcode); // 把hashcode转换为16进制的字符
        System.out.println(code);//548123ec
        String childDirectory = code.charAt(0) + File.separator + code.charAt(1); // 5/4
        // 创建指定目录
        File file = new File(storeDirectory, childDirectory);
        if (!file.exists()) {
            file.mkdirs();
        }
        return childDirectory;
    }

    // 普通表单项
    private void processFormField(FileItem fileitem) {
        try {
            String fieldname = fileitem.getFieldName();// 字段名
            String fieldvalue = fileitem.getString("UTF-8");// 字段值
            System.out.println(fieldname + "=" + fieldvalue);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

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

}