微信公众号多张图片提交给web后台存储ftp

一、流程

1、大概流程

微信公众号上报图片→→传给微信服务器→→返回媒体id=(serverId=media_id)→media_id以数组或者字符串的形式给后台

→→后台根据微信的AppID&&secret获取access_token→→然后根据access_token和media_id去微信服务器获取图片的路径

→→根据获取的路径转换为base64码→→根据base64保存到服务器本地临时路径→→然后通过读取本地临时路径文件形式传到所需要的FTP

二、编码

1、html 

  js部分斟酌使用

 

<script type="text/javascript">

        $(function () {
            alertTG();


        });
        $("#read").click(function () {

            var val = $(‘#read‘).is(":checked");

            if (val) {
                document.getElementById("qrtg").disabled = false;
                document.getElementById("qrtg").style.backgroundColor = ‘#6496fd‘;
            } else {
                document.getElementById("qrtg").disabled = true;
                document.getElementById("qrtg").style.backgroundColor = ‘#b3cdfb‘;
                //document.getElementById("qrtg").style.
            }
        });

        function closeAlertTG() {
            document.getElementById(‘light222‘).style.display = ‘none‘;
            document.getElementById(‘fade222‘).style.display = ‘none‘;
        }

        function alertTG() {

            document.getElementById(‘light222‘).style.display = ‘block‘;
            document.getElementById(‘fade222‘).style.display = ‘block‘;
        }

        //    var myDiv = document.getElementById("myDiv");
        //var bodyDiv = document.getElementById("bodyDiv");
        function hideMap() {
            // 隐藏myDiv
            $("#myDiv").hide();
            $("#bodyDiv").show();
            //    myDiv.style.display = "none";
            //bodyDiv.style.display = "block";

        }

        /* function showMap() {
            $("#bodyDiv").hide();
            $("#myDiv").show();

        } */


        var latitude; //经度
        var longitude; //纬度
        var openid = "";

        function UrlSearch() {
            var name, value;
            var str = location.href; //取得整个地址栏
            var num = str.indexOf("?")
            str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]

            var arr = str.split("&"); //各个参数放到数组里
            for (var i = 0; i < arr.length; i++) {
                num = arr[i].indexOf("=");
                if (num > 0) {
                    name = arr[i].substring(0, num);
                    value = arr[i].substr(num + 1);
                    this[name] = value;
                    if (name == ‘openid‘) {
                        openid = value;
                    }
                    ;
                }
            }
        }

        //            alert(location.href.split(‘#‘)[0])

        getEventTree("1", "1");
        getOrgidTree();
        /*$("#eventType1").change(function(){
           $("#eventType2").empty();
           if(!$("#eventType1").val()){
               document.getElementById("eventTypeDiv2").style.display="none";
               document.getElementById("eventTypeDiv3").style.display="none";
           }else{
               getEventTree("2",$("#eventType1").val());
               document.getElementById("eventTypeDiv2").style.display="block";
           }
       }); */
        $("#eventType2").change(function () {
            $("#eventType3").empty();
            if (!$("#eventType2").val()) {
                document.getElementById("eventTypeDiv3").style.display = "none";
            } else {
                getEventTree("3", $("#eventType2").val());
                document.getElementById("eventTypeDiv3").style.display = "block";
            }

        });

        function getOrgidTree() {
            var url = baseUrl + "/mobileEvent/default.do?method=getOrgidTree";
            var params = {}; //定义请求参数
            mui.ajax(url, {
                data: params,
                dataType: ‘json‘, //服务器返回json格式数据
                type: ‘post‘,
                timeout: 20000, //超时时间设置为10秒;
                success: function (data) {
                    var dataList = data.data;
                    var selid = document.getElementById("orgidselect");

                    for (var i = 0; i < dataList.length; i++) { //循环添加多个值
                        selid.options[selid.options.length] = new Option(dataList[i].orgname, dataList[i].orgid);
                    }
                },
                error: function (xhr, type, errorThrown) {
                    alert("不小心出错了")
                    //异常处理;
                    //                        plus.nativeUI.toast("连接服务器失败");
                }
            });
        }

        function getEventTree(number, typeid) {
            var url = baseUrl + interfaces.wx_getEventTree;
            var params = {}; //定义请求参数
            params.id = typeid; //首次id为空
            mui.ajax(url, {
                data: params,
                dataType: ‘json‘, //服务器返回json格式数据
                type: ‘post‘,
                timeout: 20000, //超时时间设置为10秒;
                success: function (data) {
                    var dataList = data.data;
                    var selid = "";
                    if (1 == number) {
                        selid = document.getElementById("eventType1");
                    } else if ("2" == number) {
                        selid = document.getElementById("eventType2");
                        $("#eventType2").append("<option value=‘‘>请选择</option>");
                    } else if ("3" == number) {
                        selid = document.getElementById("eventType3");
                        $("#eventType3").append("<option value=‘‘>请选择</option>");
                    }
                    for (var i = 0; i < dataList.length; i++) { //循环添加多个值
                        selid.options[selid.options.length] = new Option(dataList[i].data, dataList[i].id);
                    }
                },
                error: function (xhr, type, errorThrown) {
                    alert("不小心出错了")
                    //异常处理;
                    //                        plus.nativeUI.toast("连接服务器失败");
                }
            });
        }

        config(); //微信注入接口
        function config() {
            var url = baseUrl + ‘/JmWeChatEvent/default.do?method=getNTS‘;
            var params = {};
            params.url = location.href;
            mui.ajax(url, {
                data: params,
                dataType: ‘json‘, //服务器返回json格式数据
                type: ‘get‘,
                timeout: 20000, //超时时间设置为10秒;
                success: function (data) {
                    if (data.result) {
                        wx.config({
                            debug: false,
                            appId: ‘wxf5fb81ebcd0912df‘,
                            timestamp: data.timestamp,
                            nonceStr: data.noncestr,
                            signature: data.signature,
                            jsApiList: [
                                // 所有要调用的 API 都要加到这个列表>中
                                ‘checkJsApi‘,
                                ‘openLocation‘,
                                ‘getLocation‘,
                                ‘onMenuShareTimeline‘,
                                ‘onMenuShareAppMessage‘,
                                ‘hideAllNonBaseMenuItem‘,
                                ‘hideMenuItems‘,
                                ‘chooseImage‘,
                                ‘previewImage‘,
                                ‘uploadImage‘,
                                ‘downloadImage‘,
                            ],
                        });
                    } else {
                        alert("请求失败!");
                    }

                },
                error: function (xhr, type, errorThrown) {
                    alert("不小心出错了")
                    //异常处理;
                    //                        plus.nativeUI.toast("连接服务器失败");
                }
            });
        }

        wx.error(function (res) {
            alert(JSON.stringify(res))
            // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
        });


        function getLocation11() {
            //获取当前位置信息
            wx.getLocation({
                type: ‘wgs84‘, // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入‘gcj02‘
                success: function (res) {
                    latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
                    longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
                    //                        var speed = res.speed; // 速度,以米/每秒计
                    //                        var accuracy = res.accuracy; // 位置精度
                    getDwName(longitude, latitude);
                }
            })
        }

        function getDwName(longitude2, latitude2) {
            //alert(longitude2+","+latitude2);
            var url = "http://api.tianditu.gov.cn/geocoder?postStr={‘lon‘:" + longitude2 + ",‘lat‘:" + latitude2 + ",‘ver‘:1}&type=geocode&tk=5ac9f5cf2ae79d3c138efe2e992046b1";
            $.ajax({
                url: url,
                type: ‘GET‘,
                contentType: "application/json",
                dataType: ‘json‘,//这里要用jsonp的方式不然会报错
                success: function (data) {
                    document.getElementById("yinying1").style.display = "none";
                    var addComp = data.result.addressComponent;
                    var address = addComp.county + addComp.road + addComp.address + addComp.poi;
                    //    alert(address);
                    document.getElementById("location").value = address;
                }
            });
        }

        //点击调用摄像头
        var imgPath = ""; //图片路径
        var localData = ""; //base64文件
        document.getElementById(‘camera‘).addEventListener(‘tap‘, function () {
            wx.chooseImage({
                count: 1, // 默认9
                sizeType: [‘original‘], // 可以指定是原图还是压缩图,默认二者都有
                sourceType: [‘album‘, ‘camera‘], // 可以指定来源是相册还是相机,默认二者都有
                success: function (res) {
                    var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
                    var div = document.createElement("div");
                    div.classList.add("imgSty");
                    div.setAttribute("id", localIds);

                    var img = document.createElement("img");
                    img.src = localIds;
                    img.classList.add("imgClass");
                    div.appendChild(img);

                    var divDel = document.createElement("div");
                    divDel.classList.add("delectImg");
                    divDel.setAttribute("localIds", localIds);
                    divDel.innerHTML = "X";
                    div.appendChild(divDel);


                    var imgClassLen = mui(".imgSty");
                    if (imgClassLen.length < 6) {
                        if (imgClassLen.length > 1) {
                            document.getElementById("imgDiv").style.height = "240px"
                            if (imgClassLen.length > 4) {
                                document.getElementById("imgDiv").style.height = "280px";
                                //document.getElementById("submission").style.marginBottom ="20px"
                            }
                        } else {
                            document.getElementById("imgDiv").style.height = "180px"
                        }
                        document.getElementById("imgLoad").appendChild(div);
                    } else {
                        alert("照片只能上传六张")
                        return;
                    }
                    ;

                    wx.uploadImage({
                        localId: localIds.toString(), // 需要上传的图片的本地ID,由chooseImage接口获得
                        isShowProgressTips: 1, // 默认为1,显示进度提示
                        success: function (res) {

                            var serverId = res.serverId; // 返回图片的服务器端ID
                            img.setAttribute("serverId", serverId);
                            wx.downloadImage({
                                serverId: serverId, // 需要下载的图片的服务器端ID,由uploadImage接口获得
                                isShowProgressTips: 1, // 默认为1,显示进度提示
                                success: function (res) {
                                    var localId = res.localId; // 返回图片下载后的本地ID
                                    wx.getLocalImgData({
                                        localId: localId, // 图片的localID
                                        success: function (res) {
                                            localData = res.localData; // localData是图片的base64数据,可以用img标签显示
                                            img.setAttribute("localData", "data:image/png;base64," + localData);

                                        }
                                    });
                                }
                            });
                        }
                    });
                }
            });
        });
        //三级列表点击事件
        mui("#imgLoad").on(‘tap‘, ‘div.delectImg‘, function () {
            var localIds = this.getAttribute(‘localIds‘);
            var liitem = this;
            var btnArray = [‘确定‘, ‘取消‘];
            mui.confirm(‘确定删除所选附件?‘, ‘提示‘, btnArray, function (event) {
                if (event.index == 0) {
                    liitem.parentNode.remove(liitem.parentNode);
                } else {
                }
            });
        });
        //上传图片到微信
        //            function ulLoadToWechat(localIds) {
        //                alert(localIds)
        //                wx.uploadImage({
        //                    localId: localIds.toString(), // 需要上传的图片的本地ID,由chooseImage接口获得
        //                    isShowProgressTips: 1, // 默认为1,显示进度提示
        //                    success: function (res) {
        //                    var serverId = res.serverId; // 返回图片的服务器端ID
        //                    alert(serverId)
        //                    }
        //                });
        //            };


        //点击遮罩关闭
        //            document.getElementById(‘fade‘).addEventListener(‘tap‘, function() {
        //                document.getElementById(‘light‘).style.display = ‘none‘;
        //                document.getElementById(‘fade‘).style.display = ‘none‘
        //            })


        //提交按钮的点击事件 提交数据
        var localDataList = [];
        var media_ids = "";
        document.getElementById(‘submission‘).addEventListener(‘tap‘, function () {
            UrlSearch(); //获取openid
            var localData = mui(".imgClass");
            for (var i = 0; i < localData.length; i++) {
                var localDatajson = {};
                localDatajson.localData = localData[i].getAttribute("localData");
                localDataList.push(localDatajson)
            }

            for (var i = 0; i < localData.length; i++) {
                if ("" == media_ids) {
                    media_ids = localData[i].getAttribute("serverId");
                } else {
                    media_ids += "," + localData[i].getAttribute("serverId")
                }

            }
            var description = document.getElementById("description").value; //问题描述
            if (!description || description.length < 1) {
                alert("要填写问题描述");
                return false;
            }
            ;
            var location = document.getElementById("location").value; //事件地址
            if (!location || location.length < 1) {
                alert("要填写事件发生地点");
                return false;
            }
            ;
            var firstId = $("#eventType1").val();
            var secondId = $("#eventType2").val();
            var thirdId = $("#eventType3").val();
            if (!firstId && !secondId && !thirdId) {
                alert("您还需要选择事件类型");
                return false;
            }
            ;
            var url = baseUrl + interfaces.wx_eventReport;
            var params = {}; //定义请求参数
            params.source_type_id = "3702820402";
            params.is_sensitive = ‘0‘; //重大敏感事件(1是 0否),默认否,传0不显示
            params.is_hard = ‘0‘; //疑难事件(1是 0否),默认否,传0不显示
            params.event_level = "EVENT_LEVEL"; //紧急程度(字典key:EVENT_LEVEL),默认一般
            if (thirdId) {
                params.type_id_3 = thirdId;
            } else if (secondId) {
                params.type_id_3 = secondId;
            } else if (firstId) {
                params.type_id_3 = firstId;
            }
            params.address = location; //事件地址
            params.description = description; //问题描述
            params.flowDefKey = "jimoProcess"; //jimoProcess 固定值
            params.reportUserId = openid; //上报人id(微信的openId)
            params.position = longitude + "," + latitude; //当前所处的经纬度(以逗号隔开)
            /* params.position = ‘120.531936‘ + "," + ‘36.407288‘; //当前所处的经纬度(以逗号隔开) */
            params.saveFlag = "0"; //0上报,1暂存(区别上报还是暂存),微信端传0
            /* params.phone = "15275428813"; //当前登陆人的手机号 */
            params.fjpath = ""; //附件路径(多个以逗号隔开)
            params.fjname = ""; //附件名称(多个以逗号隔开)
            params.anonymous = $("#anonymous").val();
            params.orgid = $("#orgidselect").val();
            //"VJN5F2M6IBkRhVOGcr7Cf5eqOjib86of7Kz0Sqlx8YD6hg92KHdHQcdbBwSayGVn,VJN5F2M6IBkRhVOGcr7Cf5eqOjib86of7Kz0Sqlx8YD6hg92KHdHQcdbBwSayGVn";
            params.media_ids = media_ids;
            params.base = JSON.stringify(localDataList);
            //                params.base = "data:image/png;base64," + localData;
            document.getElementById("yinying").style.display = "block";//遮罩显示
            mui.ajax(url, {
                data: params,
                dataType: ‘json‘, //服务器返回json格式数据
                type: ‘post‘,
                timeout: 50000, //超时时间设置为10秒;
                success: function (data) {
                    document.getElementById("yinying").style.display = "none";
                    if (data.result == true) {
                        alert("上报成功,我们会尽快核查");
                        setTimeout(function () {
                            wx.closeWindow();
                        }, 800)
                    } else {
                        alert(data.message);
                        setTimeout(function () {
                            wx.closeWindow();
                        }, 800)
                    }
                },
                error: function (xhr, type, errorThrown) {
                    alert("不小心出错了")
                    setTimeout(function () {
                        wx.closeWindow();
                    }, 800)
                    //异常处理;
                    //                        plus.nativeUI.toast("连接服务器失败");
                }
            });
        });

    </script>

2、java编码

Base64Util.java

package sdcncsi.ict.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.stream.FileImageInputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @Description 图片字符串转换
 * @Author
 * @Date 2019-08-20 10:16
 */
public class Base64Util{
    /**
     * 字符串转图片
     * @param base64Str
     * @return
     */
    public static byte[] decode(String base64Str){
        byte[] b = null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            b = decoder.decodeBuffer(replaceEnter(base64Str));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return b;
    }

    /**
     * 图片转字符串
     * @param image
     * @return
     */
    public static String encode(byte[] image){
        BASE64Encoder decoder = new BASE64Encoder();
        return replaceEnter(decoder.encode(image));
    }

    public static String encode(String uri){
        BASE64Encoder encoder = new BASE64Encoder();
        return replaceEnter(encoder.encode(uri.getBytes()));
    }

    /**
     *
     * @path    图片路径
     * @return
     */

    public static byte[] imageTobyte(String path) throws IOException {
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while((numBytesRead = input.read(buf)) != -1){
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            input.close();
        }

        return data;
    }



    public static String replaceEnter(String str){
        String reg ="[\n-\r]";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }

    /**
     * 远程读取image转换为Base64字符串
     * @param imgUrl =图片地址全路径
     * @return
     */
    public static String ImageUrlBase64(String imgUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try{
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();

            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while( (len=is.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return new BASE64Encoder().encode(outStream.toByteArray());
        }catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            if(is != null)
            {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outStream != null)
            {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpUrl != null)
            {
                httpUrl.disconnect();
            }
        }
        return imgUrl;
    }

    /**
     * @Description: 获取图片对应的base64码(以文件的形式)
     * @Author: wangxa
     * @throws IOException
     * @Date: 18:25 2019/8/19
     */
    public static String getImageBase64String(File imgFile) throws IOException {
        byte[] data = new byte[0];
        BASE64Encoder encoder = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            int totalNumberBytes = inputStream.read(data);
            encoder = new BASE64Encoder();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
        }
        return encoder.encode(data);
    }

    //根据base64 和 临时图片路径,生成临时图片
    public static boolean Base64ToImage(String imgStr, String imgFilePath)
    {
        if (StringUtil.isNull(imgStr)) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; i++) {
                if (b[i] < 0)
                {
                    int tmp43_41 = i; byte[] tmp43_40 = b;tmp43_40[tmp43_41] = ((byte)(tmp43_40[tmp43_41] + 256));
                }
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();

            return true;
        }
        catch (Exception e) {}
        return false;
    }


}
TempMaterialService.java//获取临时素材路径
package sdcncsi.ict.customized.mobile.event;

import sdcncsi.ict.customized.mobile.wechat.HttpXmlClient;
import sdcncsi.ict.util.Base64Util;
import sdcncsi.ict.util.StringUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 * @Description 临时素材业务类(仅图片)
 * @Author
 * @Date 2019-11-29 10:54
 */
public class TempMaterialService {


    //定义两个成员变量常量
    //获取临时素材(视频不能使用https协议)
    public static final String GET_TMP_MATERIAL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s";
    //获取临时素材(视频)
    public static final String GET_TMP_MATERIAL_VIDEO = "http://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s";

    //获取微信服务器中生成的媒体文件

    //由于视频使用的是http协议,而图片、语音使用http协议,故此处需要传递media_id和type

    protected static String fetchTmpFile(String media_id, String type) throws IOException {
        try {
            String base64 = "";

            //获取access_token
            HttpXmlClient hxc = new HttpXmlClient();
            Map tokenMap = hxc.getAccess_token();
            String access_token = StringUtil.getStringValue(tokenMap.get("access_token"));

            String url = null;
            //视频是http协议
            if ("video".equalsIgnoreCase(type)) {
                url = String.format(GET_TMP_MATERIAL_VIDEO, access_token, media_id);
            } else {
                url = String.format(GET_TMP_MATERIAL, access_token, media_id);
            }
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("POST");
            conn.connect();
            base64 = Base64Util.ImageUrlBase64(url);

            return base64;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
HttpXmlClient.java//获取access_token
package sdcncsi.ict.customized.mobile.wechat;

import net.sf.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;


public class HttpXmlClient {


    //获取公众号Access_token
    public Map getAccess_token() {
        Map data = null;
        try {
            data = new HashMap();
            //开始定义参数获取请求
            Map<String, String> params = new HashMap<String, String>();
            params.put("corpid", "xxxx");
            params.put("corpsecret", "xxxx");

            //拼地址
            String apiUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET", params);
            //开始请求
            URL url2 = new URL(apiUrl);
            URLConnection open = url2.openConnection();
            InputStream input = open.getInputStream();
            //这里转换为String,带上包名,怕你们引错包
            String result = org.apache.commons.io.IOUtils.toString(input, "utf-8");
            JSONObject resJson = JSONObject.fromObject(result);
            String access_token = resJson.getString("access_token");

            data.put("result", true);
            data.put("access_token", access_token);

        } catch (IOException e) {
            data.put("result", false);
            data.put("access_token", "");
            e.printStackTrace();
        }

        return data;
    }
}
MobileEventController.java//主要控制类
package sdcncsi.ict.customized.mobile.event;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import sdcncsi.ict.base.attachment.Attachment;
import sdcncsi.ict.base.mobile.JsonUtils;
import sdcncsi.ict.customized.mobile.appAttachment.AppAttachment;
import sdcncsi.ict.customized.mobile.wechat.JmWeChatEvent;
import sdcncsi.ict.flow.WorkFlowService;
import sdcncsi.ict.util.*;
import sdcncsi.ict.util.cache.CacheUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 
 * @date  手机端处理Controller
 */
@Controller
@RequestMapping("/mobileEvent/default.do")
public class MobileEventController {
    private final static Logger log = LoggerFactory.getLogger(MobileEventController.class);
    public final ObjectMapper mapper = new ObjectMapper();
    @Autowired
    private WorkFlowService workFlowService;

    @RequestMapping(params = "method=eventReport")
    public void eventReport(HttpServletRequest req, HttpServletResponse response) {
        // 返回标识
        boolean result = true;
        // 提示信息
        String message = "";
        // 结果数据
        Map dataMap = new HashMap();
        try {
            Map map = RequestUtil.getMap(req);
            // 事件类型id处理
            String type_id_1 = "",type_id_2 = "";
            String[] str;
            String type_id_3 = StringUtil.getStringValue(map.get("type_id_3"));
            if (StringUtil.isNotNull(type_id_3)) {
                try {
                    if(type_id_3.length()<=4){
                        map.put("type_id_1", type_id_3);
                        map.put("type_id_3", "");
                    }else if(type_id_3.length()<=7){
                        str = type_id_3.split("\\.");
                        type_id_1 = str[0] + "." + str[1];
                        map.put("type_id_1", type_id_1);
                        type_id_2 = str[0] + "." + str[1] + "." + str[2];
                        map.put("type_id_2", type_id_2);
                        map.put("type_id_3", "");
                    }else{
                        str = type_id_3.split("\\.");
                        type_id_1 = str[0] + "." + str[1];
                        map.put("type_id_1", type_id_1);
                        type_id_2 = str[0] + "." + str[1] + "." + str[2];
                        map.put("type_id_2", type_id_2);
                    }
                } catch (Exception e) {
                    result = false;
                    message = "事件类型格式错误,上报失败!";
                }
            }
            map.remove("base");
            System.err.println("后台参数======"+map);
            String type = StringUtil.getStringValue(map.get("type"));
            String media_ids = StringUtil.getStringValue(map.get("media_ids"));//前台value是以字符串的形式,多个以逗号分隔
            String fjid = Guid.get();


            if(StringUtil.isNotNull(media_ids)){
                String[] media_id = media_ids.split(",");
                for (int i = 0; i <media_id.length ; i++) {
                    /**
                     * @Description:远程读取image转换为Base64字符串
                     * mediz_id 微信媒体id
                     * type 媒体类型(暂时写死,因为只有图片)
                     * @Date: 10:10 2019/12/2
                     */
                    //
                    String base64 = TempMaterialService.fetchTmpFile(media_id[i], "image");

                    if(StringUtil.isNotNull(base64)){
                        // 创建文件工具类
                        FileUtil fileUtil = new FileUtil();
                        Map<String, Object> map1=new HashMap<String, Object>();
                        map.put("busitype", "wxevent");
                        Attachment achment=new Attachment(map);
                        //获取文件参数配置
                        map1=achment.queryUploadParam();
                        //上传路径
                        String uploadTempPath = CacheUtil.getParamValue("uploadTempPath");
                        //图片服务器相对保存路径
                        String date = DateUtil.getCurrentTime("yyyyMMdd");//生成文件夹
                        String imgName = DateUtil.getCurrentTime("yyyyMMddHHmmss");//生成文件名  时分秒
                        String saveDirectory = StringUtil.getStringValue(map1.get("savepath")) + "/" + date;

                        //创建本地文件夹、、用自己框架封装的穿件文件夹工具类
                        AppAttachment appattachment=new AppAttachment(map);
                        boolean resultC=appattachment.createDirs(uploadTempPath + saveDirectory);

                        if(resultC==true){
                            //生成临时图片文件
                            String filename = imgName+".jpg";
                            String imgLocal = uploadTempPath+saveDirectory+"/"+filename;
                            String imgLocal1 = saveDirectory+"/"+imgName+".jpg";
                            boolean resultToImage = Base64Util.Base64ToImage(base64,imgLocal);//生成本地临时图片

                            //判断生成图片成功
                            if (resultToImage == true) {
                                boolean flag = appattachment.ftpUpload(imgLocal1);//通过本地临时图片上传ftp服务器
                                if (flag) {
                                    map.put("filePath", imgLocal1);//文件路径
                                    map.put("filename", filename);//文件名
                                    map.put("file_size", "");//文件大小
                                    map.put("file_hash", "");//文件hash值
                                    map.put("file_type", PropertyUtil.getFileType(filename));//文件类型
                                    map.put("busiid", fjid);
                                    Map<String, Object> map2 = new HashMap<String, Object>();
                                    map2 = appattachment.addFileInfo(map);
                                    map.put("fjid", fjid);
                                } else {
                                    result = false;
                                    message = "上传服务器异常!";
                                }

                            } else {
                                result = false;
                                message = "临时图片生成异常!";
                            }
                        }
                    }
                }
            }

            
            //获取用户电话号码
            //上报人id
            String reportUserId = StringUtil.getStringValue(map.get("reportUserId"));
            JmWeChatEvent jmWeChatEvent = new JmWeChatEvent(map);
            Map phoneMap=new HashMap();
            phoneMap=jmWeChatEvent.getWeChatUserPhone(reportUserId);
            map.put("phone", phoneMap.get("telphone"));
            map.put("username", phoneMap.get("username"));
            //推送消息的提醒的Map
            MobileEvent event=new MobileEvent(map);
            event.saveWXReportParameter();
            // 返回标识 true成功 false失败
            result = dataMap.get("result") == null ? true
                    : (Boolean) dataMap.get("result");
            // 返回信息
            message = result ? "上报成功!" : "上报失败!";
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
            message = "上报失败!";
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
        }
        JSONObject json = JSONObject.fromObject(JsonUtils.getReturnMap(result,
                message, null, null, dataMap));
        JsonUtils.outputJson(response, json);
    }
}

 

微信公众号多张图片提交给web后台存储ftp

上一篇:小程序setData()使用和注意事项


下一篇:easywechat微信开发SDK之小微商户进件(一)