微信服务号开发 上传多媒体文件:图片

/**
     * 通过文件上传得到文件media_id,文件名
     *
     * @param file
     * @return
     */
    public static Map<String, String> getIdByUploadFile(File file) {
        Map<String, String> map = new HashMap<String, String>();
        // 返回文件上传成功的media_id
        String media_id = "";
        String imgPath = file.getName();

        // 这里存放的是指定的目录data(一般是从配置文件中读取)
        File storeFile = new File(Const.FILE_IMG_PATH + imgPath);
        Files.copy(file, storeFile);

        String httpUrl = WXConst.FILE_URL;
        String fileType = Const.FILE_FILE_TYPE;
        String access_token = (String) Cache.get("access_token");
        String contentType = Const.FILE_CONTENT_TYPE;
        String filePath = Const.FILE_IMG_PATH;

        JSON json = new JSONObject();
        json = WXHttpUtil.UploadMedia(httpUrl, fileType, access_token, imgPath, file, contentType, filePath);
        String resultString = json.toString();
        // 将结果转换成json格式的数据
        JSONObject resultObj = json.parseObject(resultString);
        System.out.println("===media_id===>>" + resultObj.getString("media_id"));
        // 返回的结果的状态码
        if ("".equals(resultObj.getString("media_id")) || resultObj.getString("media_id") == null) {
            // 请求失败的提示信息
            System.out.println(Messages.get("upload_multimedia_files_fail") + resultObj);
        } else {
            // 请求成功返回的提示信息
            media_id = resultObj.getString("media_id");
            System.out.println(Messages.get("upload_multimedia_files_success") + resultObj);
        }
        map.put("media_id", media_id);
        map.put("imgPath", imgPath);
        return map;
    }

原文地址:https://www.cnblogs.com/xunfang123/p/4195946.html