作者:思铮同学要努力工作 | 来源:互联网 | 2023-09-12 12:40
同步的方法:publicstaticfinalStringPHOTO_FOLDER_PATHD:homewxphoto;privatestaticStringREQUEST_MED
同步的方法:
public static final String PHOTO_FOLDER_PATH = "D:/home/wxphoto/";
private static String REQUEST_MEDIA_URL =
"http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s";
AttachmentPojo attachmentPojo = new AttachmentPojo();
//同步微信和阿里云
String accessToken = HttpClientUtils.getStaticString(
domainConfig.getAuthDomain() + "/wechat/getAccessToken.html");
JSONObject rstJson = JSONObject.fromObject(accessToken);
if (rstJson != null) {
accessToken = rstJson.getString("respResult");
String strImgUrl = String.format(REQUEST_MEDIA_URL, accessToken, serverId);
String filePath = PHOTO_FOLDER_PATH + System.currentTimeMillis() + ".jpg";
dwnWxPhotoBeforeSave(attachmentPojo, serverId, strImgUrl, filePath);
}
/**
* 微信图片添加前就同步阿里云
*
* @param vo
* @param serverId
* @param imgUrl
* @param filePath
*/
private void dwnWxPhotoBeforeSave(AttachmentPojo vo, String serverId, String imgUrl, String filePath) {
byte[] data = HttpClientUtils.getBytes(imgUrl);
if (data != null) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filePath);
fos.write(data);
} catch (Exception e) {
LOGGER.error("下载微信图片{serverId:" + serverId + "}失败", e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
LOGGER.error("关闭文件流失败", e);
}
}
}
}
// 图片上传至oss服务器
//此处可参考上一篇博文取配置的路径
File file = new File(filePath);
String uploadName = FileUtils.uploadFile(data, pathConfig.getFilepath(), file.getName());
//修改本地数据库操作
this.modifyAttachVo(vo, file, uploadName, serverId);
}
//上传到阿里服务器
//此处可参考上一篇博文取配置的路径
public static String uploadFile(byte[] data, String filepath, String fileName) {
try {
String path = getAliPath(filepath, fileName);
AliUploadUtils.uploadToAliOss(path, data);
path = AliUploadUtils.aliOssPath + "/" + path;
return path;
} catch (RuntimeException e1) {
throw e1;
} catch (Exception e) {
throw new RuntimeException("文件上传 系统异常");
}
}
/**
* 上传文件到阿里云
* 此处可参考上一篇博文取配置的路径
* @param byte 文件流
* @param path 上传路径
* @return
*/
public static Boolean uploadToAliOss(String path, byte[] data) {
try {
// endpoint以杭州为例,其它region请按实际情况填写
String endpoint = AliUploadUtils.endpoint;
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录
// https://ram.console.aliyun.com 创建
String accessKeyId = AliUploadUtils.accessKeyId;
String accessKeySecret = AliUploadUtils.accessKeySecret;
// 创建OSSClient实例
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// 上传文件
ossClient.putObject(AliUploadUtils.bucketName, path, new ByteArrayInputStream(data));
// 关闭client
ossClient.shutdown();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}