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; }}