一:从微信素材库获取照片
1.获取的url
get请求
https://qyapi.weixin.qq.com/cgi-bin/media/get
2.需要的参数
@Data
@ApiModel(value = "CompanyWeChatUploadImgDto", description = "企业微信图片上传实体类")
public class CompanyWeChatUploadImgDto implements Serializable {
private static final long serialVersionUID = 6708935565631318783L;
@ApiModelProperty("秘钥")
@NotBlank(message = "秘钥不能为空")
private String accessToken;
@ApiModelProperty("图片位置id")
@NotBlank(message = "图片位置id不能为空")
private String mediaId;
}
accessToken和mediaId都是由前端人员传递,后台负责接收就行
3.使用restTemplate远程调用获取图片
String url = weChatUrl+ "?access_token=" + accessToken + "&media_id=" + mediaId;
ResponseEntity<byte[]> exchange = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class);
我们将exchange的返回值定义为byte数组,方便后续转化
4.将byte数组转化为inputStream
byte[] data = exchange.getBody();
InputStream inputStream = new ByteArrayInputStream(data);
5.将inputStream写入图片要上传的路径
String imgUrl = "image/20221207135456/photo.jpg";
File newFile = new File(imgUrl );
FileUtils.copyInputStreamToFile(inputStream, newFile);
二:将流文件上传目标服务器
1.上传文件
//上传文件
boolean upload = uploadImg(newFile, imgUrl);
2.代码实现
/**
* 上传文件到服务器
*
* @param uploadFile 文件
* @param imgUrl 文件路径
* @return 是否上传
*/
public boolean uploadImg(File uploadFile, String imgUrl) {
if (!uploadFile.exists()) {
return false;
}
try {
// 创建ObsClient实例
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
PutObjectResult putObjectResult = obsClient.putObject(bucketName, imgUrl, uploadFile);
if (putObjectResult.getStatusCode() == HttpServletResponse.SC_OK) {
return true;
}
return false;
} catch (Exception e) {
log.error("文件上传失败obs,文件名:{}", imgUrl);
return false;
} finally {
//删除本地文件
uploadFile.deleteOnExit();
}
}
三:从上传的服务器获取图片路径
public void dealImgUrl(HttpServletResponse response, String imgUrl) throws IOException {
// 创建ObsClient实例
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
ObsObject obsObject = obsClient.getObject(bucketName, imgUrl);
OutputStream os = response.getOutputStream();
InputStream is = obsObject.getObjectContent();
// 只允许 jpeg,png 和 gif
try {
if (pictureKey.endsWith(".jpeg")) {
response.setContentType("image/jpeg");
}
if (pictureKey.endsWith(".png")) {
response.setContentType("image/png");
}
if (pictureKey.endsWith(".gif")) {
response.setContentType("image/gif");
}
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.flush();
} catch (Exception e) {
log.error("FileManagementUtils.downloadFile error = {}", e);
throw e;
} finally {
is.close();
os.close();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/84085.html