继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

ServletFileUpload类上传文件工具类

car
关注TA
已关注
手记 83
粉丝 56
获赞 363

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();
            }

        }
    }
}```
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP