标签:vol 头像 java over url OLE data ola gen
一、控制层传参:Images(要上传的图片)
@Autowired
private ImageUploadServiceImpl imageUploadService;
public Object imagesAdd(@RequestParam(value = "Images", required = false) MultipartFile[] Images) {
if (Images != null && Images.length > 0) {
String images = "[";
if (Images != null && Images.length > 0) {
for (int i = 0; i < Images.length; i++) {
String imageUrl = imageUploadService.uploadFile(Images[i]);
if (i == 0) {
images += imageUrl;
continue;
} else {
images += "," + imageUrl;
}
}
}
images += "]";
}
return images;
2、服务层,上传图片
@Service
public class ImageUploadServiceImpl implements ImageUploadService {
// endpoint以杭州为例,其它region请按实际情况填写
static String endpoint = "*******";
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建
static String accessKeyId = "*******";
static String accessKeySecret = "*******";
static String bucketname = "*******";
private volatile static OSSClient ossClient;
// @Autowired
// ExceptionLogService exceptionLogService;
@Autowired
StorageServiceImpl storageObjectService;
@Autowired
MemberServiceImpl memberService;
public ImageUploadServiceImpl() {
if (ossClient == null) {
synchronized (this) {
if (ossClient == null) {
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
}
}
}
@Override
public String uploadFile(MultipartFile imgFile) {
String avatarUrl = null;
try {
// 生成一个MD5加密计算摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 计算md5函数
md.update(imgFile.getBytes());
String md5 = new BigInteger(1, md.digest()).toString(16);
StorageObject storageObject = storageObjectService.findByMd5code(md5);
if (storageObject == null) {
ObjectMetadata meta = new ObjectMetadata();
meta.setContentLength(imgFile.getSize());
String guessContentType = imgFile.getContentType();
meta.setContentType(guessContentType);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String data = sdf.format(new Date());
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//获得文件后缀名称
String imageName = guessContentType.substring(guessContentType.indexOf("/") + 1);
String fileId = data + "/" + uuid + "." + imageName;
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketname, fileId, imgFile.getInputStream());//上传文件
putObjectRequest.setMetadata(meta);
ossClient.putObject(putObjectRequest);//上传图片
storageObject = new StorageObject();
storageObject.setCreateTime(new Date());
storageObject.setMd5(md5);
StringBuffer url = new StringBuffer("http://");
url.append(bucketname).append(".").append(endpoint).append("/").append(fileId);
storageObject.setUrl(url.toString());
storageObjectService.save(storageObject);
}
avatarUrl = storageObject.getUrl().toString();
} catch (IOException e) {
throw new ServiceException("上传头像出错");
} catch (NoSuchAlgorithmException e) {
throw new ServiceException("上传头像出错");
}
return avatarUrl;
}
}
标签:vol 头像 java over url OLE data ola gen
原文地址:https://www.cnblogs.com/qqzhulu/p/10582659.html