weui上传文件完整例子,后台Java接受,SSM框架,要解决的问题是接受2张以上图片

谷亚彬 发布于 2017/11/30 09:57
阅读 3K+
收藏 1

weUI的Uploader组件,目前已实现的功能是,一个input type=file,上传图片,有压缩预览,最多6张,每读取一张,js就添加了节点预览一张,但是表单直接提交时,后台获得的是文件标签最后一次操作读取的图片。后台只接收到一张图片,我需要接收全部6张图片;直接看码;不要base64,没用PHP,我后台要Java接收,技术难点:前端怎么获取最多6张图片,并存储到数组里面传到后台!

<#include "../../common/page.ftl" />
<!doctype html>
<html lang="zh-Hans">
<head>
<@header/>
    <script src="${base}/weui/zepto.min.js"></script>
    <link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/0.3.0/weui.css">
    <script src="https://cdn.bootcss.com/zepto/1.1.6/zepto.min.js"></script>

</head>
<body ontouchstart  class="page-bg">

<div>
  <form action="${base}/life/lifeServeInfoAddOrUpdate" method="post" enctype="multipart/form-data">

    <div>
        <select  name="classCode" id="classCode"  lay-search="">
            <option value="">选择分类</option>
        <#list scSysCodeTypeList as scSysCodeType>
            <option disabled="disabled" value="${(scSysCodeType.codeType)!}">${(scSysCodeType.codeTypeName)!}</option>
            <#list scSysCodeList as scSysCode>
                <#if scSysCode.codeType! ==scSysCodeType.codeType>
                <option value="${(scSysCode.sysCodeId)!}">${(scSysCode.codeDesc1)!}</option>
                </#if>
            </#list>
        </#list>
        </select>
    </div>

    <div>
        <input type="text" placeholder="填写标题,4-30个字符" id="billTitle" name="billTitle" value=""/>
    </div>

    <div>
        <textarea placeholder="填写文本,不少于10个字符" rows="15" cols="30" id="documentText" name="documentText" value=""></textarea>
    </div>

    <div class="container">
    <#--<div class="weui_cells_title">&lt;#&ndash;上传图片&ndash;&gt;</div>-->
        <div class="weui_cells weui_cells_form">
            <div class="weui_cell">
                <div class="weui_cell_bd weui_cell_primary">
                    <div class="weui_uploader">
                        <div class="weui_uploader_hd weui_cell">
                            <div class="weui_cell_ft js_counter">0/6</div>
                        </div>
                        <div class="weui_uploader_bd">
                            <ul class="weui_uploader_files">
                                <!-- 预览图插入到这 --> </ul>
                            <div class="weui_uploader_input_wrp">
                                <input id="lifeServeInfofile" name="lifeServeInfofile" value="" class="weui_uploader_input js_file" type="file" accept="image/jpg,image/jpeg,image/png,image/gif" multiple=""></div>
                                <img type="hidden" id="photoServerSite1" name="photoServerSite1"/>

                        </div>
                        <div class="weui_cell_bd weui_cell_primary">最多上传6张,每张不超过5M,支持jpg,jpeg,png,gif</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="weui_dialog_alert" style="display: none;">
        <div class="weui_mask"></div>
        <div class="weui_dialog">
            <div class="weui_dialog_hd"> <strong class="weui_dialog_title">警告</strong>
            </div>
            <div class="weui_dialog_bd">弹窗内容,告知当前页面信息等</div>
            <div class="weui_dialog_ft">
                <a href="javascript:;" class="weui_btn_dialog primary">确定</a>
            </div>
        </div>
    </div>

    <div>
        ¥<input type="text" placeholder="填输入价格" id="prix" name="prix" value=""/>
    </div>

    <div>
        <input type="text" placeholder="请填写您的称呼" id="linkman" name="linkman" value=""/>
    </div>

    <div>
        <input type="text" placeholder="填写您的联系方式" id="contactWay" name="contactWay" value=""/>
    </div>

    <div>
        <input type="submit" value="发布" id=""/>
    </div>
   </form>
</div>

</body>
</html>

<script>

    $.weui = {};
    $.weui.alert = function(options) {
        options = $.extend({
            title: '警告',
            text: '警告内容'
        }, options);
        var $alert = $('.weui_dialog_alert');
        $alert.find('.weui_dialog_title').text(options.title);
        $alert.find('.weui_dialog_bd').text(options.text);
        $alert.on('touchend click', '.weui_btn_dialog', function() {
            $alert.hide();
        });
        $alert.show();
    };

    $(function() {
        // 允许上传的图片类型
        var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
        // 1024KB,也就是 1MB
        var maxSize = 1024 * 1024;
        // 图片最大宽度
        var maxWidth = 300;
        // 最大上传图片数量
        var maxCount = 6;
        $('.js_file').on('change', function(event) {
            var files = event.target.files;



            // 如果没有选中文件,直接返回
            if (files.length === 0) {
                return;
            }

            for (var i = 0, len = files.length; i < len; i++) {
                var file = files[i];
                var reader = new FileReader();

                // 如果类型不在允许的类型范围内
                if (allowTypes.indexOf(file.type) === -1) {
                    $.weui.alert({
                        text: '该类型不允许上传'
                    });
                    continue;
                }

                if (file.size > maxSize) {
                    $.weui.alert({
                        text: '图片太大,不允许上传'
                    });
                    continue;
                }

                if ($('.weui_uploader_file').length >= maxCount) {
                    $.weui.alert({
                        text: '最多只能上传' + maxCount + '张图片'
                    });
                    return;
                }

                reader.onload = function(e) {
                    var img = new Image();
                    img.onload = function() {
                        // 不要超出最大宽度
                        var w = Math.min(maxWidth, img.width);
                        // 高度按比例计算
                        var h = img.height * (w / img.width);
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        // 设置 canvas 的宽度和高度
                        canvas.width = w;
                        canvas.height = h;
                        ctx.drawImage(img, 0, 0, w, h);
                        //只有这个函数的第一个参数为image/jpeg是压缩功能才可正常使用,还可以写第二个参数,比如0.8为压缩比例
                        var base64 = canvas.toDataURL('image/png');

                        // 插入到预览区
                        var $preview = $('<li class="weui_uploader_file weui_uploader_status" style="background-image:url(' + base64 + ')"><div class="weui_uploader_status_content">0%</div></li>');
                        $('.weui_uploader_files').append($preview);
                        var num = $('.weui_uploader_file').length;
                        $('.js_counter').text(num + '/' + maxCount);

                        // 然后假装在上传,可以post base64格式,也可以构造blob对象上传,也可以用微信JSSDK上传

                        var progress = 0;

                        function uploading() {
                            $preview.find('.weui_uploader_status_content').text(++progress + '%');
                            if (progress < 100) {
                                setTimeout(uploading, 30);
                            } else {
                                // 如果是失败,塞一个失败图标
                                //$preview.find('.weui_uploader_status_content').html('<i class="weui_icon_warn"></i>');
                                $preview.removeClass('weui_uploader_status').find('.weui_uploader_status_content').remove();
                            }
                        }
                        setTimeout(uploading, 30);
                    };

                    img.src = e.target.result;
                };

                reader.readAsDataURL(file);

            }
        });
    });
</script>
@RequestMapping(value = "lifeServeInfoAddOrUpdate" ,method = RequestMethod.POST )
    public String lifeServeInfoAddOrUpdate(@RequestParam("lifeServeInfofile") MultipartFile lifeServeInfofile, LifeServeInfo lifeServeInfo, Model model) {

        //判断文件夹是否存在
        File dest = new File(UPLOAD_DIR);
        if (!dest.exists()) {
            dest.mkdirs();
        }

        String fi = lifeServeInfofile.getOriginalFilename().toLowerCase();
        // 扩展名
        String fileNameExtension = fi.substring(fi.indexOf("."), fi.length());
        // 实际存储的真实文件名
        String realName = UUID.randomUUID().toString() + fileNameExtension;

        //检查文件扩展名是否为图片
        boolean allowed = Arrays.asList(UPLOAD_IMAGE_ALLOWED_TYPE).contains(fileNameExtension);
        if (!allowed) {
            model.addAttribute("message", "不支持的类型");
            return "lifeServePublishInfo";
        }
        //检查文件大小,限制5M
        if (lifeServeInfofile.getSize() > UPLOAD_IMAGE_MAXSIZE_MB * 1024 * 1024) {
            model.addAttribute("message", "图片大小不可超过" + UPLOAD_IMAGE_MAXSIZE_MB + "M");
            return "lifeServePublishInfo";
        }

        try {
            Files.copy(lifeServeInfofile.getInputStream(), Paths.get(UPLOAD_DIR, realName));
            model.addAttribute("message", "上传成功!文件名:" + realName);
            model.addAttribute("imageUrl", request.getContextPath() + "/upfiles/" + realName);
        } catch (IOException | RuntimeException e) {
            model.addAttribute("message", "上传文件失败:" + e.getMessage());
        }

        lifeServeInfo.setPhotoServerSite(request.getContextPath() + "/upfiles/" + realName);

        System.out.println(lifeServeInfo.getClassCode()+"1111111111111111111111111");
        System.out.println(lifeServeInfo.getBillTitle()+"2222222222222222222222222");
        System.out.println(lifeServeInfo.getDocumentText()+"33333333333333333333333");
        System.out.println(lifeServeInfo.getPhotoServerSite()+"444444444444444444444");
        System.out.println(lifeServeInfo.getPrix()+"555555555555555555555555555555");
        System.out.println(lifeServeInfo.getLinkman()+"666666666666666666666666666");
        System.out.println(lifeServeInfo.getContactWay()+"7777777777777777777777777");
        Date date=new Date();
        System.out.println(date);
        lifeServeInfo.setSystemTime(date);
        lifeServeInfo.setWeixinId("zhonghe-0000000000001");
        lifeServeInfo.setStatusAs(1);
        lifeServeInfo.setIsTop(1);
        lifeServeInfo.setPageView(0);
        if (StringTools.empty(lifeServeInfo.getInfoId())){
            iLifeServeInfoService.insert(lifeServeInfo);
        }
        /*发布完之后跳转到我发布的信息集合页面去*/
        return lifeServeInfoMyPublishList(lifeServeInfo.getWeixinId(),model);
        //return "/life/lifeServeInfoMyPublishList";
    }

 

加载中
0
Asdybing
Asdybing

你的后台循环都没有,貌似是只能接受到单个文件吧

谷亚彬
谷亚彬
现在打了断点,我要看到那个对象是个数组,你说的循环已经试过了,它接收的就是最后一次操作选择的图片
0
z
zb1489631449157

是不是weui不支持多文件上传啊,没有用过,不太清楚~

返回顶部
顶部