2.2.2 显示已有封面
- 提供变量
将变量上传组件绑定
查询详情时,将封面图片路径添加变量中
2.3 后端测试数据
"/avatar/upload") (publicBaseResultavatarUpload(MultipartFilefile) { Stringurl="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80"; returnBaseResult.ok("上传成功", url); }
2.4 后端实现
2.4.1 搭建环境
- 添加坐标
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.15.0</version></dependency>
2.4.2 配置类
- yml 配置
aliyun: oss: file: pathProtocol: httpsendpoint: oss-cn-shanghai.aliyuncs.comkeyId: LTAI5t7oNGMkQJ1X8RqtLet2keySecret: 这里是密码dirName: avatarbucketName: czxy-lt
配置类packagecom.czxy.zx.course.oss; importlombok.Data; importorg.springframework.boot.context.properties.ConfigurationProperties; importorg.springframework.stereotype.Component; /*** @author 桐叔* @email liangtong@itcast.cn*/prefix="aliyun.oss.file") (publicclassOssProperties { privateStringpathProtocol; //路径协议privateStringendpoint; //地域privateStringkeyId; //账号privateStringkeySecret; //密码privateStringdirName; //上传目录privateStringbucketName; //Bucket 名称}
2.4.2 上传工具类
packagecom.czxy.zx.course.oss; importcom.aliyun.oss.OSS; importcom.aliyun.oss.OSSClientBuilder; importcom.czxy.zx.exception.EduException; importorg.springframework.stereotype.Component; importorg.springframework.web.multipart.MultipartFile; importjavax.annotation.Resource; importjava.io.FileInputStream; importjava.io.IOException; importjava.io.InputStream; /*** @author 桐叔* @email liangtong@itcast.cn*/publicclassOssUtils { privateOssPropertiesossProperties; publicStringupload(MultipartFilefile) { if(file==null) { thrownewEduException("上传文件为空"); } try { // 创建OSSClient实例。OSSossClient=newOSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getKeyId(), ossProperties.getKeySecret()); Stringpath=ossProperties.getDirName() +"/"+System.currentTimeMillis() +".png"; // 数据流InputStreaminputStream=file.getInputStream(); // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。ossClient.putObject(ossProperties.getBucketName(), path, inputStream); // 关闭OSSClient。ossClient.shutdown(); Stringurl=ossProperties.getPathProtocol() +"://"+ossProperties.getBucketName()+"."+ossProperties.getEndpoint()+"/"+path; returnurl; } catch (IOExceptione) { thrownewEduException("文件上传有误"); } } }
2.4.3 上传功能
注入工具
调用工具
privateOssUtilsossUtils; "/avatar/upload") (publicBaseResultavatarUpload(MultipartFilefile) { Stringurl=ossUtils.upload(file); returnBaseResult.ok("上传成功", url); }