1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java对接天翼云OOS实现文件存储

java对接天翼云OOS实现文件存储

时间:2020-04-30 13:41:14

相关推荐

java对接天翼云OOS实现文件存储

java对接天翼云OOS实现文件存储

1. 注册天翼云账户、开通对象存储、创建容器2. 获取AccessKeyID、SecretAccessKey确定四个参数,在application.yml中填入以下配置 3. maven中央仓库中没有该jar包,官网下载java-oos-sdk-6.5.3.jar到本地,或者上传到maven私服下4. 下载后放入项目lib目录下,在pom.xml文件中添加相关依赖5. 添加配置类6. 实现工具类,这里直接写成Service服务类,方法一样,可进行适当修改

1. 注册天翼云账户、开通对象存储、创建容器

2. 获取AccessKeyID、SecretAccessKey

确定四个参数,在application.yml中填入以下配置

# 文件上传 OOS (天翼云)oos:config:access-key: 填入之前获取的AccessKeyIDsecret-key: 填入对应密钥SecretAccessKeyendpoint: oos-(可以直接填此端点,不需要动)bucket: 容器名称

3. maven中央仓库中没有该jar包,官网下载java-oos-sdk-6.5.3.jar到本地,或者上传到maven私服下

下载链接 java-oos-sdk

4. 下载后放入项目lib目录下,在pom.xml文件中添加相关依赖

<!--天翼云OOS--><dependency><groupId>cn.ctyun</groupId><artifactId>ctyun-sdk-oss</artifactId><version>6.5.0</version><scope>system</scope><systemPath>${project.basedir}/lib/oos-java-sdk-6.5.3.jar</systemPath></dependency><dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.8</version></dependency><dependency><groupId>org.sejda.imageio</groupId><artifactId>webp-imageio</artifactId><version>0.1.6</version></dependency><!-- /artifact/joda-time/joda-time --><dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId></dependency>

5. 添加配置类

@Data@Componentpublic class OosClientConfig {@Value("${oos.config.access-key}")private String accessKey;@Value("${oos.config.secret-key}")private String secretKey;@Value("${oos.config.endpoint}")private String endpoint;@Value("${oos.config.bucket}")private String bucket;@Beanpublic AmazonS3 oosClient() {ClientConfiguration clientConfig = new ClientConfiguration();// 设置连接的超时时间,单位毫秒clientConfig.setConnectionTimeout(30 * 1000);// 设置 socket 超时时间,单位毫秒clientConfig.setSocketTimeout(30 * 1000);clientConfig.setProtocol(Protocol.HTTP); //设置 http// 设置 V4 签名算法中负载是否参与签名,关于签名部分请参看《OOS 开发者文档》S3ClientOptions options = new S3ClientOptions();options.setPayloadSigningEnabled(true);// 创建 clientAmazonS3 oosClient = new AmazonS3Client(new PropertiesCredentials(accessKey, secretKey), clientConfig);// 设置 endpointoosClient.setEndpoint(endpoint);//设置选项oosClient.setS3ClientOptions(options);return oosClient;}}

6. 实现工具类,这里直接写成Service服务类,方法一样,可进行适当修改

@Log4j2@Servicepublic class OosService {@Autowiredprivate OosClientConfig oosClientConfig;/*** @Desecription: 上传文件*/public String uploadFile(MultipartFile file, String fileName) {InputStream inputStream = null;String pathUrl = "";try {inputStream = file.getInputStream();AmazonS3 ossClient = oosClientConfig.oosClient();String remoteFilePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());String dir = remoteFilePath + "/"; // 用户上传文件时指定的前缀。// 创建上传Object的MetadataObjectMetadata objectMetadata = new ObjectMetadata();objectMetadata.setCacheControl("no-cache");objectMetadata.setHeader("Pragma", "no-cache");String suffix = fileName.substring(fileName.lastIndexOf("."));String path = dir + IdWorker.getIdStr() + suffix;try {objectMetadata.setContentLength(inputStream.available());// 上传文件log.info("开始上传文件到oss");log.info("bucket: " + oosClientConfig.getBucket());log.info("path: " + path);log.info("inputStream: " + inputStream);log.info("objectMetadata: " + objectMetadata);ossClient.putObject(oosClientConfig.getBucket(), path, inputStream, objectMetadata);// URL url = ossClient.generatePresignedUrl(new GeneratePresignedUrlRequest(oosClientConfig.getBucket(), path));String url = generatePresignedUrl(path);pathUrl = url;} catch (Exception e) {log.error("上传文件到oos失败", e);} finally {if (ossClient != null) {((AmazonS3Client) ossClient).shutdown();}if (inputStream != null) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}return pathUrl;} catch (Exception e) {log.error(e.getMessage(), e);}return null;}/*** @Desecription: 删除文件*/public boolean deleteFile(String filePath, String fileName) {AmazonS3 ossClient = oosClientConfig.oosClient();String path = filePath + fileName;boolean exist = ossClient.doesBucketExist(oosClientConfig.getEndpoint());if (!exist) {log.error("从OSS存储删除的文件不存在,path={}", path);return false;} else {try {ossClient.deleteObject(oosClientConfig.getEndpoint(), path);} catch (Exception e) {log.error("从天翼云OSS删除文件出错,path={}", path, e);return false;} finally {if (ossClient != null) {try {((AmazonS3Client) ossClient).shutdown();} catch (AmazonClientException e) {e.printStackTrace();}}}return true;}}/*** @Desecription: 获取文件下载地址 ,并设置过期时间*/public String generatePresignedUrl(String fileKey) throws ParseException {GeneratePresignedUrlRequest request = newGeneratePresignedUrlRequest(oosClientConfig.getBucket(), fileKey);/* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");Date expireDate = sdf.parse("2031-01-01");request.setExpiration(expireDate);*/URL url = oosClientConfig.oosClient().generatePresignedUrl(request);return url.toString();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。