使用FileUpload上传文件的主要Java代码

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

 
import java.io.File;
import java.io.IOException;
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;
 
public class UploadServlet extends HttpServlet {
 
    @SuppressWarnings("unchecked")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("--------------upload-----------");
 
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024); // 设置缓存大小,单位KB
        String path = request.getRealPath("/upload"); // 得到当前项目upload目录的绝对路径
        factory.setRepository(new File(path)); // 设置文件临时存储路径为path
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> list = upload.parseRequest(request);
            for (FileItem item : list) {
                // 如果item是普通表单字段
                if (item.isFormField()) {
                    String name = item.getFieldName(); // 得到表单字段的name属性值
                    String value = item.getString("gbk"); // 得到表单字段值,编码采用gbk
                    request.setAttribute(name, value);
                } else {
                    String name = item.getFieldName();
                    String value = item.getName(); // 得到上传文件的路径(根据浏览器不同可能会有所差异)
                    int start = value.lastIndexOf("\\");
                    String fileName = value.substring(start + 1); // 截取最后一个\之后的字符,即行到上传文件名
                    request.setAttribute(name, fileName);
 
                    item.write(new File(path, fileName)); // 在硬盘上写入文件
 
                    // 自己用流写的方法
                    // OutputStream os = new FileOutputStream(new
                    // File(path,fileName));
                    // InputStream is = item.getInputStream();
                    // byte[] buffer = new byte[500];
                    // int length = 0;
                    // while((length = is.read(buffer))>0){
                    // os.write(buffer, 0, length);
                    // }
                    // os.close();
                    // is.close();
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        request.getRequestDispatcher("upload/result.jsp").forward(request,
                response);
    }
}