这是代码
@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("上传临时素材失败");
}
获取时名字就是乱码的
你好,看截图应该是在上传临时素材的时候就已经乱码了,需要确认下上传的格式是不是utf-8
来设置文件名,但还是乱码的。该在哪里设置这个格式呢
关于企业微信上传临时素材,用自建应用发送素材名称乱码问题的解决方案(下载素材接口也是一样)
语言:python 3.10
解决过程:
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 ""
您好,请教一下这个问题解决了吗,如何解决的?
请问上传文件时,文件名需要做encodeURL(filename)处理吗?