在yml文件配置属性,使用@Value进行注入
@Component public class AliOSSUtils { //外部属性注入 @Value("${aliyun.oss.endpoint}") String endpoint ; // @Value("${aliyun.oss.accessKeyId}") @Value("${aliyun.oss.accessKeySecret}") String accessKeyId ; @Value("${aliyun.oss.accessKeySecret}") String accessKeySecret; @Value("${aliyun.oss.bucketName}") String bucketName; /** * 实现上传图片到OSS */ public String upload(MultipartFile file) throws IOException { // 获取上传的文件的输入流 InputStream inputStream = file.getInputStream(); // 避免文件覆盖 String originalFilename = file.getOriginalFilename(); String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf(".")); //上传文件到 OSS OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); ossClient.putObject(bucketName, fileName, inputStream); //文件访问路径 String url = "https://web-galvintlias.oss-cn-beijing.aliyuncs.com/"+ fileName; // 关闭ossClient ossClient.shutdown(); return url;// 把上传到oss的路径返回 } }
在controller中使用
@PostMapping("/upload") public Result upload(MultipartFile image) throws IOException { log.info("文件上传{}",image.getOriginalFilename()); String url= aliOSSUtils.upload(image);//调用工具类上传文件 log.info("文件上传完成:{}" ,url); return Result.success(url);//返回路径 }标签:java,String,--,OSS,Value,url,aliyun,上传,oss From: https://blog.csdn.net/Galvincat/article/details/140191451