一、OSS基本配置
1.1 基本属性配置
aliyun.oss.file.endPoint=xxxxxxxxxx
aliyun.oss.file.keyId=xxxxxxxx
aliyun.oss.file.keySecret=xxxxxxxxxxxx
aliyun.oss.file.bucketName=xxxxxxx
1.2 OSS初始化配置
package com.zhmsky.oss.utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
@Api("OSS配置文件获取工具类")
public class OssPropertiesUtil implements InitializingBean {
@Value("${aliyun.oss.file.endPoint}")
private String endPoint;
@Value("${aliyun.oss.file.keyId}")
private String keyId;
@Value("${aliyun.oss.file.keySecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketName}")
private String bucketName;
@ApiModelProperty("地域节点")
public static String END_POINT;
@ApiModelProperty("阿里云key")
public static String KEY_ID;
@ApiModelProperty("阿里云密钥")
public static String KEY_SECRET;
@ApiModelProperty("水桶名")
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT=endPoint;
KEY_ID=keyId;
KEY_SECRET=keySecret;
BUCKET_NAME=bucketName;
}
}
InitializingBean是Spring提供的拓展性接口,InitializingBean接口为bean提供了属性初始化后的处理方法,它只有一个afterPropertiesSet方法,凡是继承该接口的类,在bean的属性初始化后都会执行该方法。
二、service
package com.zhmsky.oss.service;
import org.springframework.web.multipart.MultipartFile;
public interface OssService {
String uploadOssAvatar(MultipartFile file);
}
2.1 serviceImpl
package com.zhmsky.oss.service.impl;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.zhmsky.oss.service.OssService;
import com.zhmsky.oss.utils.OssPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Service
public class OssServiceImpl implements OssService {
@Override
public String uploadOssAvatar(MultipartFile file) {
String endpoint = OssPropertiesUtil.END_POINT;
String accessKeyId = OssPropertiesUtil.KEY_ID;
String accessKeySecret = OssPropertiesUtil.KEY_SECRET;
String bucketName = OssPropertiesUtil.BUCKET_NAME;
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
String url = "";
try {
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = file.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
fileName = uuid + "-" + fileName;
String datePath = new DateTime().toString("yyyy/MM/dd");
fileName = datePath + "/" + fileName;
ossClient.putObject(bucketName, fileName, inputStream);
url = "https://" + bucketName + "." + endpoint + "/" + fileName;
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return url;
}
}
三、controller
@RestController
@RequestMapping("/ossService/file")
@Api("OSS云对象存储")
@CrossOrigin
public class OssController {
@Autowired
private OssService ossService;
@PostMapping("/uploadOssFile")
@ApiOperation("头像上传")
public Result<Map<String,String>> uploadOssFile(@ApiParam("获取上传文件") MultipartFile file) {
String url=ossService.uploadOssAvatar(file);
Map<String, String> map = new HashMap<>();
map.put("url",url);
return new ResultUtil<Map<String,String>>().setData(map);
}
}
四、前端
3.1 html
<el-form-item label="图片显示实例">
<el-upload
:show-file-list="false"
<!-- 上传成功后执行-->
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:action="BASE_API + '/ossService/file/uploadOssFile'"
class="avatar-uploader"
>
<img :src="courseInfo.cover" />
</el-upload>
</el-form-item>
3.2 js
handleAvatarSuccess(res,file) {
this.courseInfo.cover=res.result.url
},
beforeAvatarUpload(file) {
const isJPG = file.type === "image/jpeg";
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error("上传头像图片只能是 JPG 格式!");
}
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!");
}
return isJPG && isLt2M;
}
到此大功告成!
|