关于企业微信上传临时素材,用自建应用发送素材名称乱码问题的解决方案(下载素材接口也是一样) 语言:python 3.10 解决过程: 先尝试在开放社区搜索类似问题的解决方案,搜索的结果是,有很多人提出这个问题,我挨个查看,尝试了评论里的一些建议,但是,好像都不好使(也可能是使用姿势不对)。找了一通,没解决问题,算了,干脆自己试着分析下吧。从乱码的结果上看,%BC%这种像是被编码了两次,顺这这个猜测,尝试使用 [代码]requests_toolbelt[代码] 库来创建更加规范的 multipart/form-data 请求(避免被重复编码),结果呢,还就真的把问题解决了,你敢信。。。下面给出代码(python) from requests_toolbelt.multipart.encoder import MultipartEncoder async def upload_file2wecom(file_name): access_token = await get_wecom_token() file_path = get_ppt_file_path(file_name) url = f"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=file" # Read the file content as binary with open(file_path, 'rb') as f: file_content = f.read() # Create form data m = MultipartEncoder( fields={ 'media': (file_name, file_content, 'application/octet-stream') } ) async with aiohttp.ClientSession() as session: headers = { 'Content-Type': m.content_type } async with session.post(url, data=m.to_string(),headers=headers) as response: if response.status == 200: json_resp = json.loads(await response.text()) print( "upload_file2wecom:", f"result:{str(json_resp)}") if json_resp["errcode"] == 0: return json_resp["media_id"] else: return "" else: print(f"Failed to upload file. Response: {await response.text()}") return ""
上传临时素材中文文件名乱码?这是代码 @Test public void testUploadMedia() { FileSystemResource resource = new FileSystemResource("/Users/lanyanhua/Desktop/中文名.jpg"); String mediaId = uploadMedia(resource); System.out.println("mediaId:" + mediaId); //3xyN1by2qk0dVfEwKJ2ZvC4LA38qGprE3xMRbr5U6h2g //3XmJgRO7QE9mH_WCaYNgE4ETur61Few3MKTL79lzCYiWTa_Re2Q2CLX5OsCeYmAg- } /** * 上传临时素材 * * @param resource 文件 * @return media_id,该media_id仅三天内有效 */ public String uploadMedia(FileSystemResource resource) { String url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE" .replace("ACCESS_TOKEN", token).replace("TYPE", "image"); RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); param.add("file", resource); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(param, headers); ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class); if (responseEntity.getStatusCode() == HttpStatus.OK) { JSONObject body = responseEntity.getBody(); if (body.getInteger("errcode") == 0) { return body.getString("media_id"); } } throw new BusinessException("上传临时素材失败"); } 获取时名字就是乱码的 [图片]
08-09