阿里云OSS图片上传

1.引入依赖

               
        
            com.aliyun.oss
            aliyun-sdk-oss
            3.15.1
        

2.配置

阿里云OSS图片上传_第1张图片

 3.0创建实体对象

@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliOSSProperties {
    private String endpoint ;
    private String accessKeyId ;
    private String accessKeySecret ;
    private String bucketName ;
}

4.0在工具类引入实体

@Component
public class AliOSSUtils {
@Autowired
private AliOSSProperties aliOSSProperties;
    /**
     * 图片上传oss
     */
    public String upload(MultipartFile multipartFile) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        // 避免文件覆盖
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(aliOSSProperties.getEndpoint(), aliOSSProperties.getAccessKeyId(),aliOSSProperties.getAccessKeySecret());
        ossClient.putObject(aliOSSProperties.getBucketName(), fileName, inputStream);

        //文件访问路径
        String url = aliOSSProperties.getEndpoint().split("//")[0] + "//" + aliOSSProperties.getBucketName() + "." + aliOSSProperties.getEndpoint().split("//")[1] + "/" + fileName;

        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }
}

在controller层调用工具类实现图片上传

@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private AliOSSUtils aliOSSUtils;
    @PostMapping
    public Result upload(MultipartFile image) throws Exception {
        String url = aliOSSUtils.upload(image);
        return Result.success(url);
    }
}

你可能感兴趣的:(阿里云,数据库,服务器)