@Slf4j
@Component
public class CustomerService {
private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token" +
"=%s&type=image";
@Autowired
private RestTemplate restTemplate;
@Autowired
private AccessTokenHelper accessTokenHelper;
/**
* 把媒体文件上传到微信服务器,获取上传图片的media_id
*
* @return 上传图片的media_id
*/
public String uploadTempMedia(MultipartFile file) throws IOException {
String accessToken = accessTokenHelper.getAccessToken();
log.info(accessToken);
if (StringUtils.isBlank(accessToken)) {
log.error("access_token为空");
return null;
}
String url = String.format(UPLOAD_URL, accessToken);
MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpHeaders pictureHeader = new HttpHeaders();
pictureHeader.setContentType(MediaType.parseMediaType(Objects.requireNonNull(file.getContentType())));
pictureHeader.setContentDispositionFormData("file", UUID.randomUUID() + ".PNG");
HttpEntity<ByteArrayResource> picturePart = new HttpEntity<>(new ByteArrayResource(file.getBytes()),
pictureHeader);
multipartRequest.add("file", picturePart);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multipartRequest, headers);
String result = restTemplate.postForObject(url, requestEntity, String.class);
log.info(result);
//{"type":"image","media_id":"TQMWXsRHEu9qHrMIiQ7VwygS1f4fDIoO4oHEbpFdAemOW56QiIEHOrCVVsHHqjBF","created_at":1615949444,"item":[]}
if (!StringUtils.isBlank(result)) {
JSONObject jsonObject = JSONObject.parseObject(result);
return jsonObject.getString("media_id");
}
return null;
}
}