/**
* @author: xuebl
* @Date: 2022/5/6
* @Description: 校准本地阿里云文件路径
*/
@RequestMapping(params = "doAliPathEdit")
@ResponseBody
public void doAliPathEdit(HttpServletRequest request, ModelMap modelMap, HttpServletResponse response,
OutputStream output) throws UnsupportedEncodingException {
try {
String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = KEYID;
String accessKeySecret = KEYsecret;
String bucketName = 文件夹名;
/**********************************************************************************************************/
//获取所有符合条件的附件数据,准备统一刷数据
String sql = "select id,note,realpath from t_s_attachment \n" +
" where ifnull(osspath,'')=''\n" +
" and ifnull(note,'')!=''\n" +
" order by createdate desc" ;
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
int sussesNum = 0;
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = list.get(i);
String id = "";
String note = "";
String realpath = "";
if(oConvertUtils.isNotEmpty(map.get("id"))){
id = String.valueOf(map.get("id"));
}
if(oConvertUtils.isNotEmpty(map.get("note"))){
note = String.valueOf(map.get("note"));
}
if(oConvertUtils.isNotEmpty(map.get("realpath"))){
realpath = String.valueOf(map.get("realpath"));
}
if(StringUtil.isNotEmpty(id)&&StringUtil.isNotEmpty(note)&&StringUtil.isNotEmpty(realpath)){
//开始处理
String fileName = realpath.substring(realpath.lastIndexOf("/"));//获取文件名
String aliPath = note+fileName; //阿里云路径 是用note拼接 '/'加 文件名得到的
// 创建OSSClient实例。
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// 列举 该文件下所有的文件
/*ObjectListing objectListing = ossClient.listObjects(bucketName, "");
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
for (OSSObjectSummary s : sums) {
System.out.println(s.getKey()+"--"+s.getSize()+"---");
}*/
//判断阿里云该路径下文件是否存在
Boolean result=ossClient.doesObjectExist(bucketName,aliPath);
//System.out.println(result);
// 关闭OSSClient。
ossClient.shutdown();
if(result){
//如果存在,则返回阿里云路径保存到本地 附件表的osspath 字段
Date expiration = new Date(new Date().getTime() + 3600l * 10000 * 24 * 365 * 10);
//获取文件路径
URL url2 = ossClient.generatePresignedUrl(bucketName, aliPath, expiration);
//System.out.println(url2);
//修改osspath
sql = " update t_s_attachment set osspath = '"+url2+"' where id= '"+id+"'";
jdbcTemplate.update(sql);
sussesNum++;
}
}
}
System.out.println(">>>>>>>>成功校准"+sussesNum+"条数据");
} catch (Exception e) {
e.printStackTrace();
}
}