使用webUploader上传文件时前台添加自定义参数(java后台获取)

使用webUploader上传文件时前台添加自定义参数(java后台获取)_第1张图片

webuploader的使用,这里就不多说了,官网上一大把!http://fex.baidu.com/webuploader/

实现如图所示功能:需引入:commons-fileupload.jar

js: 

uploader.on('uploadBeforeSend', function (obj, data) {
    //传入表单参数
    data = $.extend(data, {
        "age": "18",
        "name": "John"
    });
});

java后台使用ServletFileUpload来获取表单参数(包括file类型和普通表单数据类型):

注意:使用ServletFileUpload需要禁掉 multipartResolver组件,如:


public void uploader(HttpServletRequest request) {
    boolean flag = ServletFileUpload.isMultipartContent(request);
    if (flag) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        // 解析request请求
        try {
            List list = upload.parseRequest(request);
            for (FileItem item : list) {
                //是否是普通表单类型
                if (item.isFormField()) {
                    if ("age".equals(item.getFieldName())) {
                        age = item.getString("UTF-8");
                    }
                    if ("name".equals(item.getFieldName())) {
                        name = item.getString("UTF-8");
                    }
                } else {
                    //该表单项是file类型
                        File file = new File("自定义path");
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        String fieldName = item.getName();
                        File uploaderPath = new File(file, fieldName);
                        //上传
                        item.write(uploaderPath)              
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

你可能感兴趣的:(实现小功能)