1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > springboot+vue实现上传头像文件到阿里云对象存储oss

springboot+vue实现上传头像文件到阿里云对象存储oss

时间:2019-02-08 22:42:18

相关推荐

springboot+vue实现上传头像文件到阿里云对象存储oss

在阿里云oss上创建一个bucket,获取四个信息:

编写工具类,提供对外调用四个信息的方法:

//当项目一启动,就执行接口的方法,读取配置文件内容@Componentpublic 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;//给外界提供公用方法调用变量,防止外界修改变量@Overridepublic void afterPropertiesSet() throws Exception {END_POINT = endpoint;KEY_ID = keyid;KEY_SECRET = keysecret;BUCKET_NAME = bucketname;}}

实现serviceImpl:

@Servicepublic class OssServiceImpl implements OssService {@Overridepublic 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 {// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);// 获取上传文件输入流。InputStream inputStream = file.getInputStream();//使用随机唯一参数,将 - 去除String uuid = UUID.randomUUID().toString().replaceAll("-", "");//调用oss方法实现上传/** 第一个参数:bucket名称* 第二个参数:上传到oss的文件路径或名称,可以使用file.getOriginalFilename()获取* 第三个参数:上传文件输入流* */String fileName = file.getOriginalFilename();fileName = uuid + fileName;//将上传的文件按照日期进行分类String dateTime = new DateTime().toString("yyyy/MM/dd");//拼接;/12/09/121231hu1231kk213killer.jpgfileName = dateTime + "/" + fileName;ossClient.putObject(bucketName, fileName, inputStream);// 关闭OSSClient。ossClient.shutdown();//吧上传到oss文件路径手动拼接出来,进行返回//https://zf-.oss-cn-/kill.jpgString 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-cropperv-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}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。