【微信公众号】微信公众号接口-上传图片到微信服务器

前台的实现我们可以参考https://blog.csdn.net/Evan_QB/article/details/81776013

图片上传地址:

/** 上传图片素材*/
    public static final String URL_UPLOAD = "https://api.weixin.qq.com/cgi-bin/material/add_material?type=image&access_token=token"

后台部分我们可以在后面进行添加

@PostMapping("/uploadImages")
@ResponseBody
public String uploadImages(HttpServletRequest request,MultipartFile file){
    try{
        String filename = file.getOriginalFilename();
        //上传的路径
        String path = "d:\\upload";
        filename = changeName(filename);
        String rappendix = "upload/" + filename;
        filename = path + File.separator + filename;
        File file1 = new File(filename);
        file.transferTo(file1);
        String str = "{\"src\":\"" + rappendix + "\"}";
        //将本地的路径上传到服务器上
        String imgUrl = WxCardUtil.postFile(UrlConstant.URL_UPLOAD, filename);
        //将返回的imgUrl保存到数据库中
        imgService.save(imgUrl);

        return str;
    }catch (Exception e){
        e.printStackTrace();
        throw new AuthorizationException("上传文件失败");
    }
}

向微信服务器发起请求postFile方法:

/*
 * 调微信接口上传永久图片
 */
public static String postFile(String url, String filePath) throws IOException {
    File file = new File(filePath);
    if (!file.exists()) {
        throw new IOException("文件不存在");
    }
    String result = null;
    try {
        URL url1 = new URL(url);
        // 连接
        HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
        /**
         * 设置关键值
         */
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(30000);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);  // post方式不能使用缓存
        conn.setRequestMethod("POST");  // 以Post方式提交表单,默认get方式
        // 设置请求头信息
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Cache-Control", "no-cache");
        // 设置边界
        String boundary = "-----------------------------" + System.currentTimeMillis();
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        // 请求正文信息
        OutputStream output = conn.getOutputStream();
        output.write(("--" + boundary + "\r\n").getBytes());
        output.write(
                String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName())
                        .getBytes());
        output.write("Content-Type: image/jpeg \r\n\r\n".getBytes());
        byte[] data = new byte[1024];
        int len = 0;
        FileInputStream input = new FileInputStream(file);
        while ((len = input.read(data)) > -1) {
            output.write(data, 0, len);
        }
        output.write(("\r\n--" + boundary + "\r\n\r\n").getBytes());
        output.flush();
        output.close();
        input.close();
        InputStream resp = conn.getInputStream();
        StringBuffer sb = new StringBuffer();
        while ((len = resp.read(data)) > -1)
            sb.append(new String(data, 0, len, "utf-8"));
        resp.close();
        result = sb.toString();
        //System.out.println(result);
    } catch (ClientProtocolException e) {
        log.error("postFile,不支持http协议", e);
    } catch (IOException e) {
        log.error("postFile数据传输失败", e);
    }
    System.out.println(result);
    //将字符串转换成jsonObject对象
    JSONObject jsonObject = JSONObject.fromObject(result);
    String imgurl = jsonObject.getString("url");
    log.info(imgurl);
    return imgurl;
}

结果如下:

上传之后我们可以在微信公众号的素材管理中看到

【微信公众号】微信公众号接口-上传图片到微信服务器_第1张图片

【微信公众号】微信公众号接口-上传图片到微信服务器_第2张图片

 

 

 

 

 

你可能感兴趣的:(①java学习,------,微信公众号)