- 在阿里云oss上创建一个bucket,获取四个信息:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/44e0a3dae1b06907915adbfe0fe20646.png)
- 编写工具类,提供对外调用四个信息的方法:
@Component
public class ConstantPropertiesUtils 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;
public static String END_POINT;
public static String KEY_ID;
public static String KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
KEY_ID = keyid;
KEY_SECRET = keysecret;
BUCKET_NAME = bucketname;
}
}
- 实现serviceImpl:
@Service
public class OssServiceImpl implements OssService {
@Override
public String uploadAvatar(MultipartFile file) {
String endpoint = ConstantPropertiesUtils.END_POINT;
String accessKeyId = ConstantPropertiesUtils.KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
try {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
InputStream inputStream = file.getInputStream();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String fileName = file.getOriginalFilename();
fileName = uuid + fileName;
String dateTime = new DateTime().toString("yyyy/MM/dd");
fileName = dateTime + "/" + fileName;
ossClient.putObject(bucketName, fileName, inputStream);
ossClient.shutdown();
String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
return url;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
- 前端使用vue的头像上传组件:
<el-form>
<!-- 讲师头像 -->
<el-form-item label="讲师头像">
<!-- 头像缩略图 -->
<pan-thumb :image="teacherVo.avatar"/>
<!-- 文件上传按钮 -->
<el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更换头像
</el-button>
<!--
v-show:是否显示上传组件
:key:类似于id,如果一个页面多个图片上传控件,可以做区分
:url:后台上传的url地址
@close:关闭上传组件
@crop-upload-success:上传成功后的回调 -->
<image-cropper
v-show="imagecropperShow"
:width="300"
:height="300"
:key="imagecropperKey"
:url="BASE_API+'/eduoss/fileoss'"
field="file"
@close="closeImage"
@crop-upload-success="cropSuccess"/>
</el-form-item>
closeImage() {
this.imagecropperShow = false
},
cropSuccess(data) {
this.imagecropperShow = false
this.teacherVo.avatar = data.url
}