jsp和servlet进行数据上传

2022-11-13 11:02:02 浏览数 (1)

代码语言:javascript复制
public class uploadservlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("文件传发来");
//        ServletInputStream inputStream=req.getInputStream();
//        byte[] buffrt=new byte[1024000];
//        int read = inputStream.read(buffrt);
//        System.out.println(new String(buffrt,0,read));
        //(只有是多段数据才是文件上传)
        if(ServletFileUpload.isMultipartContent(req))
        {
            //创建工厂实现类
            FileItemFactory fileItemFactory=new DiskFileItemFactory();
            //创建用于解析上传数据的工具类
            ServletFileUpload servletFileUpload=new ServletFileUpload(fileItemFactory);
            try {
                //解析上传的数据,得到每一个表单项
                List<FileItem> list=servletFileUpload.parseRequest(req);
                for(FileItem fileItem :list)
                {
                    if(fileItem.isFormField())
                    {
                        System.out.println("表单项的name属性值"  fileItem.getName());
                        System.out.println("表单项的value的属性值"  fileItem.getString("UTF-8"));
                    }
                    else
                    {
                        System.out.println("表单项的name属性值"  fileItem.getFieldName());
                        System.out.println("上传的文件名" fileItem.getName());
                        fileItem.write(new File("D:\" fileItem.getName()));
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

这个流程步骤很重要!!!!记住他

0 人点赞