手记

ServletFileUpload类上传文件工具类


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

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

public class UploadUtil {

    public ServletFileUpload getFileUpload(String savePath) {
        File file = new File(savePath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        return upload;

    }

    public void uploadFile(List<FileItem> items, String savePath)
            throws IOException {
        for (FileItem item : items) {

            if (!item.isFormField()) {
                String filename = item.getName();
                if (filename == null || "".equals(filename.trim())) {
                    continue;
                }
                filename = filename.substring(filename.lastIndexOf("\\") + 1);
                InputStream in = item.getInputStream();
                FileOutputStream out = new FileOutputStream(savePath + "\\"+ filename);
                byte buffer[] = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                in.close(); 
                out.close();
                item.delete();
            }

        }
    }
}```
0人推荐
随时随地看视频
慕课网APP