1、控制层传参:Images(要上传的图片)安全
@Autowired
private ImageUploadServiceImpl imageUploadService;app
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 += "]";dom
}ide
return images;函数
二、服务层,上传图片ui
@Service
public class ImageUploadServiceImpl implements ImageUploadService {this
// 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; }}