微信公众号之上传图片(本地和网络)

版权声明:本文为博主原创文章,欢迎大家多多指教 https://blog.csdn.net/u012954706/article/details/82587087

前言

1、Controller


/**
 *
 * @param strings
 * @throws Exception
 */
@Value("${wechat_erweimaEmptUrl}")
private String wechat_erweimaEmptUrl;




@ApiOperation(value = "输入path生成图片",notes = "输入path生成图片",
        consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE,
        response = ResponseBean.class)
@ApiImplicitParams({
        @ApiImplicitParam(name = "filePath", value = "图片路径", paramType = "query", dataTypeClass = String.class),
        @ApiImplicitParam(name = "type", value = "1 本地文件路径 2、网络图片路径", paramType = "query", dataType = "int"),
        @ApiImplicitParam(name = "weChatBusinessNoId", value = "数据库中存放微信运营者的,主键,服务区号哆趣商城 3: ",paramType = "query", dataType = "long")
})
@PostMapping("/image/creteImage")
@ResponseBody
public ResponseBean creteImage(String filePath,Integer type,Long weChatBusinessNoId){
    FileOutputStream   outputStream = null;
    File file = null;
    try {
        if(type==2){
            file = new File(wechat_erweimaEmptUrl+UUIDGenerator.generate()+ ".jpg");
            outputStream = new FileOutputStream(file);
            URL u = new URL(filePath);
            BufferedImage imageQR = ImageIO.read(u);
            ImageIO.write(imageQR, "jpg", outputStream);

        }else {
            file = new File(filePath);
        }
        return ResponseBean.buildSuccess(WeChatUploadUtil.uploadMediaToWXGetMedia(file, WeChatBusinessNoUtil.findById(weChatBusinessNoId)));
    } catch (AppException e) {
        log.error(e.getMessage(),e);
        return ResponseBean.buildFailure(e.getCode(),e.getMessage());
    } catch (Exception e) {
        log.error(e.getMessage(),e);
        return ResponseBean.buildFailure(e.getMessage());
    }finally {//关闭不必要的连接
        try {
            if (outputStream != null) {
                outputStream.close();
            }
            //图片生成将服务器文件删除
            if(type==2){
                file.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

2、上传代码

package com.duodian.youhui.admin.utils.wechat;

import com.duodian.youhui.admin.constants.WechatApiUrlParams;
import com.duodian.youhui.admin.constants.WechatMenuParams;
import com.duodian.youhui.admin.utils.wechat.AccessToakeUtil;
import com.duodian.youhui.entity.db.wechat.WeChatBusinessNo;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Desc:
 * @Author HealerJean
 * @Date 2018/5/28  下午3:16.
 */
@Slf4j
public class WeChatUploadUtil {


    public static String uploadMediaToWXGetMedia(File file,WeChatBusinessNo weChatBusinessNo) throws IOException {
        if (!file.exists()) {
            log.error("文件不存在!");
            return null;
        }

        //此处改为自己想要的结构体,替换即可
        String access_token= AccessToakeUtil.getAccessToaken(weChatBusinessNo);

        String type = "image";
        String url = WechatApiUrlParams.UPLOAD__MEDIA_URL+access_token+"&type="+type+"";
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");

        // 设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="
                + BOUNDARY);

        // 请求正文信息

        // 第一部分:
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // ////////必须多两道线
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
                + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");

        byte[] head = sb.toString().getBytes("utf-8");

        // 获得输出流
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(head);

        // 文件正文部分
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();

        // 结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线

        out.write(foot);

        out.flush();
        out.close();

        /**
         * 读取服务器响应,必须读取,否则提交不成功
         */
        try {
            // 定义BufferedReader输入流来读取URL的响应
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            conn.disconnect();
            String mediaId = JSONObject.fromObject(buffer.toString()).getString("media_id");
            log.info("mediaId:"+mediaId);
            return  mediaId;
        } catch (Exception e) {
            log.error("发送POST请求出现异常!" + e);
            e.printStackTrace();
        }
        return null;
    }




/**
 * 从微信服务器下载多媒体文件
 *
 * @author qincd
 * @date Nov 6, 2014 4:32:12 PM
 */
public static String downloadMediaFromWx(String fileSavePath,WeChatBusinessNo weChatBusinessNo,String mediaId) throws IOException {

    String download_media_url =WechatApiUrlParams.DOWNLOAD_MEDIA_URL;

    //此处改为自己想要的结构体,替换即可
    String access_token= AccessToakeUtil.getAccessToaken(weChatBusinessNo);


    String requestUrl = download_media_url.replace("ACCESS_TOKEN", access_token).replace("MEDIA_ID", mediaId);
    URL url = new URL(requestUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    InputStream in = conn.getInputStream();

    File dir = new File(fileSavePath);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    if (!fileSavePath.endsWith("/")) {
        fileSavePath += "/";
    }

    String ContentDisposition = conn.getHeaderField("Content-disposition");
    String weixinServerFileName = ContentDisposition.substring(ContentDisposition.indexOf("filename")+10, ContentDisposition.length() -1);
    fileSavePath += weixinServerFileName;
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileSavePath));
    byte[] data = new byte[1024];
    int len = -1;

    while ((len = in.read(data)) != -1) {
        bos.write(data,0,len);
    }

    bos.close();
    in.close();
    conn.disconnect();

    return fileSavePath;
}




}





如果满意,请打赏博主任意金额,感兴趣的在微信转账的时候,添加博主微信哦, 请下方留言吧。可与博主自由讨论哦

支付包 微信 微信公众号
支付宝 微信 微信公众号

猜你喜欢

转载自blog.csdn.net/u012954706/article/details/82587087