
在实际开发中有上传文件的需求除了可以使用上传到本地服务器也可以选中上传到阿里OSS进行存储这里将从阿里云控制台创建桶开始进行实现阿里oss部分获取keysecret首页右上角我的-选中“AccessKey”会有如下弹框选择继续选择创建(有上限有2个key会置灰)拿到keysecret后需要自己保存好连接OSS是必须要用到的只显示这一次丢失无法找回创建桶搜索“OSS对象存储”选择控制台创建可以直接创建或是进入列表再创建快捷创建输入bucket名名称不可重复创建好后需要设置下阻止公共访问和读写权限都打开Java工具类数据源这里需要四项数据endpoint、accessKeyId、accessKeySecret、bucketName可以直接在工具类中编写为了后续便于修改可以写在配置文件中# 名称可以进行自定义aliyun.oss.endpointhttps://oss-cn-beijing.aliyuncs.comaliyun.oss.accessKeyIdaliyun.oss.accessKeySecretaliyun.oss.bucketName可以将四项数据抽取到一个类中通过注解实现调用配置文件中的数据importlombok.Data;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.stereotype.Component;ComponentConfigurationProperties(prefixaliyun.oss)DatapublicclassAliOSSProperties{//直接通过属性去properties文件中匹配值,调用时使用get方法//oss终端地址privateStringendpoint;//key-idprivateStringaccessKeyId;//key-secretprivateStringaccessKeySecret;//创建的桶名privateStringbucketName;}工具类importcom.aliyun.oss.OSS;importcom.aliyun.oss.OSSClientBuilder;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;importorg.springframework.web.multipart.MultipartFile;importjava.io.IOException;importjava.io.InputStream;importjava.util.UUID;//添加容器控制 进行properties读值ComponentpublicclassOSSUtils{/*Value(${aliyun.oss.endpoint}) //可以通过value注解直接获取到配置文件中的数据 private String endpoint ;*///通过实体类进行数据的获取通过get方法AutowiredprivateAliOSSPropertiesproperties;//将上传的文件作为参数进行传递publicStringupload(MultipartFilefile)throwsIOException{//获取文件输入流InputStreaminputStreamfile.getInputStream();//生成新的文件名通过uuid避免文件名重复并拼接源文件的后缀名StringnewFileNameUUID.randomUUID()file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(.));//上传图片到客户端先创建客户端OSSossClientnewOSSClientBuilder().build(properties.getEndpoint(),properties.getAccessKeyId(),properties.getAccessKeySecret());//进行上传ossClient.putObject(properties.getBucketName(),newFileName,inputStream);//生成可以访问上传文件的地址StringBufferstringBuffernewStringBuffer(properties.getEndpoint());stringBuffer.insert(8,properties.getBucketName().).append(/).append(newFileName);ossClient.shutdown();returnstringBuffer.toString();}}工具类创建好后直接调用使用就可以了String upload ossUtils.upload(上传的文件参数名); “upload”是返回的文件可访问地址