java-web实现文件的上传

public String addProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        
            try {
                //1创建hashmap来接收页面的数据
                HashMap map =new HashMap<>();
            
                //2创建文件项对象
                DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        
                //3创建文件上传对象
                ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
                
                //4通过文件上传对象解析所有数据,用集合保存
                List filelist = fileUpload.parseRequest(request);
                
                //5通过foreach循环遍历集合中的数据
                for (FileItem fItem : filelist) {
                    
                    //判断是否是普通的上传控件
                    if (fItem.isFormField()) {
                        
                        map.put(fItem.getFieldName(), fItem.getString("utf-8"));
                        
                    } else {
                        // 获取上传组件的名字
                        String name = fItem.getName();
                    
                        //为了文件安全,打乱文件的名字
                        String uuidName = UploadUtils.getUUIDName(name);
                        
                        //设置文件上传的位置
                        String path = this.getServletContext().getRealPath("/img2/product/other");
                        
                        //输入流
                        InputStream input = fItem.getInputStream();
                        
                        //输出流
                        FileOutputStream output = new FileOutputStream(new File(path, uuidName));
                    
                        //对拷
                        IOUtils.copy(input, output);
                        
                        //关闭资源
                        input.close();
                        output.close();
                        
                        //将文件和文件路径存储到map集合里去
                        map.put(fItem.getFieldName(), "/img2/product/other/" + uuidName);
                    }
                }
                //封装product数据
                Product product = new Product();
                BeanUtils.populate(product, map);
                
                //手动设置product无法自己添加的数据,
                product.setPid(UUIDUtils.getId());
                
                product.setPdate(new Date());
                
                Category c = new Category();
                
                c.setCid((String)map.get("cid"));
                
                product.setCategory(c);
                
                ps.addProduct(product);
                
                response.sendRedirect(request.getContextPath()+"/adminProduct?method=findAllProduct");
            } catch (Exception e) {
                e.printStackTrace();
            }

你可能感兴趣的:(java-web实现文件的上传)