jdbc编程遇到文件上传

【jdbc编程】

问题一:ps.setObject(i + 1, params[i])乱码,url未编码或者编码添加的位置不正确

我的是由jdbc:mysql://localhost:3306/mytest?createDatabaseIfNotExist=true&allowMultiQueries=true&autoReconnect=true&useUnicode=true&zeroDateTimeBehavior=convertToNull&characterEncoding=UTF-8改为jdbc:mysql://172.16.1.212:3306/mytest?characterEncoding=UTF-8&ampcreateDatabaseIfNotExist=true&allowMultiQueries=true&autoReconnect=true&useUnicode=true&zeroDateTimeBehavior=convertToNull,问题解决

问题二:

1、上传文件使用spring-mvc框架,可以导入commons-io和commons-upload的jar包,借用

        MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
        MultipartFile file = mreq.getFile("file");

即可获取上传的文件。

2、使用原生jdbc上传文件,可借用DiskFileItemFactory和ServletFIleUpload将request中的请求数据取出,这里需要注意因为表单使用了enctype="multipart/form-data" method="post",所以request.getParameter();获取不到数据,我的处理是用把通过DiskFileItemFactory和ServletFileUpload获取的请求数据封装到map集合里,然后就可以正常取值判断了。

private synchronized Map<String, String> getReqData(HttpServletRequest req, int type) throws Exception {
        req.setCharacterEncoding("utf-8");
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        Map<String, String> reqMap = new HashMap<String, String>(9);
        String epFileName = null;
        String filePath = null;
        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                List<FileItem> items = upload.parseRequest(req);
                // 循环items获取上传文件后缀名
                for (FileItem item : items) {
                    if (!item.isFormField() && !StringUtil.isNullOrEmpty(item.getName())) {
                        epFileName = item.getName();
                    }
                }
                for (FileItem item : items) {
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String value = item.getString("UTF-8");
                        reqMap.put(fieldName, value);
                    } else {
                        if (!StringUtil.isNullOrEmpty(epFileName)) {
                            // String path =
                            // req.getSession().getServletContext().getRealPath("\\upload");//
                            // 服务器路径
                            String path = "E:uploadPic"; // 本地路径
                            // String path = "/EasybuySystem2/WebRoot/upload"
                            // \\ 代表创建子文件夹
                            filePath =
                                path + "\\" + DateUtil.format(new Date(), "yyyyMMdd") + "\\"
                                    + epFileName.replace(".", "" + DateUtil.format(new Date(), "HHmmssSSS") + ").");
                            File newFile = new File(filePath);
                            String fileName = item.getName();
                            if (!StringUtil.isNullOrNot(fileName)) {
                                item.write(newFile);
                            }
                        }
                    }
                }
            } catch (FileUploadException e) {
                // 失败,删除本地上传的文件
                this.delLocalFile(filePath);
                filePath = null;
                log.debug("为上传图片新建本地名称,getFilePath方法发生异常,uri=" + req.getRequestURL());
            }
        }
        log.debug("为上传图片新建本地名称, 文件路径:filePath=" + filePath);
        log.debug("为上传图片新建本地名称, 数据reqMap=" + reqMap);
        reqMap.put("epFileName", epFileName);
        reqMap.put("epFilePath", filePath);
        return reqMap;
    }
    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 途径一:使用DiskFileItemFactory,https://blog.csdn.net/qq_31463999/article/details/79197375
        // 途径二:使用multipartFile强转request
        Map<String, String> reqMap = getReqData(req, 0);
        String epName = reqMap.get("epName");
        String epDesc = reqMap.get("epDesc");
        String epPriceStr = reqMap.get("epPrice");
        String epStockStr = reqMap.get("epStock");
        String epcParentId = reqMap.get("epcParentId");
        String epQrcode = reqMap.get("epQrcode");
        String epFileName = reqMap.get("epFileName");
        String filePath = reqMap.get("epFilePath");

        // qrcode从toAddJSP跳转时随机生成,条形码以io流读入数据库;字段(qrcode)
        // 获取上传图片信息,页面可控制大小范围
        // 方式一,存入数据库(采用)--字段(picture);方式二,存到本地(blob字段使用遇到问题)
        if (StringUtil.isAnyNullOrEmpty(epName, epDesc, epPriceStr, epcParentId, epFileName)) {
            // 参数错误
            req.setAttribute(ConstantUtil.MESSAGE_ERROR, ConstantUtil.ILLEGAL_PARAM);
            if (!StringUtil.isNullOrEmpty(filePath)) {
                this.delLocalFile(filePath);
            }
        } else {
            double epPrice = StringUtil.toDouble(epPriceStr, 0.00);
            int epStock = StringUtil.toInt(epStockStr, 0);
            if (!StringUtil.isNullOrEmpty(filePath)) {
                Product product =
                    new Product(IdUtil.getSeqNo(), epName, epDesc, epPrice, epStock, epcParentId, epQrcode, epFileName);
                product.setEpfilePath(filePath);
                if (ps.add(product)) {
                    req.setAttribute(ConstantUtil.MESSAGE_ERROR, ConstantUtil.SUCCESS_ADD);
                } else {
                    this.delLocalFile(filePath);
                    req.setAttribute(ConstantUtil.MESSAGE_ERROR, ConstantUtil.FAIL_ADD);
                }
            }
        }
        req.setAttribute(ConstantUtil.URI, DEFAULT_URI);
        req.getRequestDispatcher("msg-result.jsp").forward(req, resp);
    }

时间问题,以后有时间再做进一步总结!无论如何,bug总是事出有因

猜你喜欢

转载自www.cnblogs.com/huakaiyoushi/p/10618900.html