开通成功后,打开管理控制台 创建AccessKey密钥,包含id和密码
配置yml中aliyun的信息,默认不提醒,适用于service注入属性
server: port: 7002 spring: application: name: oss-service aliyun: oss: file: endpoint: oss-cn-beijing.aliyuncs.com keyid: keysecret: bucketname: aaa-hdw-eduservice层实现
import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.hdw.ossService.service.OssService; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.io.InputStream; import java.util.UUID; @Service public class OssServiceImpl implements OssService { @Value("${aliyun.oss.file.endpoint}") private String endpoint; @Value("${aliyun.oss.file.keyid}") private String accessKeyId; @Value("${aliyun.oss.file.keysecret}") private String accessKeySecret ; @Value("${aliyun.oss.file.bucketname}") private String bucketname ; //图片上传 public String uploadImage(MultipartFile file) { try { // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 上传文件流。 InputStream inputStream = file.getInputStream(); //构建日期路径:avatar/2019/02/26/文件名 String filePath = new DateTime().toString("yyyy/MM/dd"); //文件名:uuid.扩展名 String original = file.getOriginalFilename(); //获取上传的文件名 a.jpg String fileName = UUID.randomUUID().toString(); String fileType = original.substring(original.lastIndexOf(".")); String newName = fileName + fileType; String fileUrl = filePath + "/" + newName; ossClient.putObject(bucketname,fileUrl , inputStream); // 关闭OSSClient。 ossClient.shutdown(); return "http://"+bucketname+"."+endpoint+"/"+fileUrl; }catch (Exception e){ e.printStackTrace(); } return null; } }控制层controller
@RestController @Api(tags = "图片上传") @RequestMapping("ossService/eduoss") public class OssController { @Autowired private OssService ossService; @PostMapping("/uploadimage") @ApiOperation("上传头像") public R upLoadImage(MultipartFile file){ String url = ossService.uploadImage(file); return R.ok().data("url",url); } }