当前位置:网站首页>Alibaba cloud OSS - object storage service (tool)

Alibaba cloud OSS - object storage service (tool)

2022-06-26 10:46:00 Slightly drunk CC

Alibaba cloud SDK(Java) file

One 、 rely on

<!-- Alicloud file management service -->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.10.2</version>
</dependency>

Two 、yaml To configure

# Alibaba cloud OOS Service global configuration 
aliyun:
  oss:
  	#yourEndpoint Fill in Bucket The region corresponding to Endpoint. East China 1( Hangzhou ) For example ,Endpoint Fill in for https://oss-cn-hangzhou.aliyuncs.com.
    end-point: your endpoint # You can also fill in your own domain name ( See the official website for details )
    # Alicloud account AccessKey Have all the API Access rights of , The risk is high . It is highly recommended that you create and use it RAM The user carries out API Visit or daily operations , Please log in RAM Console creation RAM user .
    accessKey-id: your accessKeyId
    secret: your secret
    # Storage space is what you use to store objects (Object) The container of , All objects must belong to a storage space .
    bucket-name: your bucketName

3、 ... and 、OSS Tool class

notes : At present, only a single file upload has been completed 、 Batch file deletion , Other functions need to be improved …

/** * @Description * @Author cb * @Date 2022-01-06 11:25 **/
@Setter
@Getter
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class OSSUtils {
    

    private String endPoint;
    private String accessKeyId;
    private String secret;
    private String bucketName;

    /** *  Upload the local file to the directory of the target storage space  * @param file  Files to upload  * @return  Return the network path of the file  */
    public String uploadFileStream(MultipartFile file) {
    
        //System.out.println(endPoint+"."+accessKeyId+"."+secret+"."+bucketName);
        InputStream inputStream = null;
        //  establish OSSClient example .
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secret);
        //  Get the stream from the uploaded file 
        try {
    
            inputStream = file.getInputStream();
            String oldName = file.getOriginalFilename();
            int lastIndexOf = oldName.lastIndexOf(".");// Before the suffix  .  The index of 
            // Get the new filename ( original file name +UUID+ Suffix name )
            String fileName= oldName.substring(0,lastIndexOf)+"-"+UUID.randomUUID().toString().replaceAll("-","")+oldName.substring(lastIndexOf);
            // The directory structure of the file to be saved , It's like 20220102 Third level directory of 
            String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            fileName=dir+"/"+fileName;

            //  establish PutObjectRequest object .
            //  Fill in... In turn Bucket name ( for example examplebucket)、Object The full path ( for example exampledir/exampleobject.txt) And the full path of the local file .Object The full path cannot contain Bucket name .
            //  If no local path is specified , By default, the file is uploaded from the local path corresponding to the project to which the sample program belongs .
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);

            //  If you need to upload, set the storage type and access permission , Please refer to the following example code .
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            //  Upload files .
            ossClient.putObject(putObjectRequest);

            // https://bucketName.endPoint/ Path to file ( Catalog + file name ),%s Is a placeholder for a string 
            String url=String.format("https://%s.%s/%s",bucketName,endPoint,fileName);
            System.out.println(" Upload file path :"+url);
            return url;
        } catch (IOException e) {
    
            throw new RuntimeException(" Failed to upload file ");
        }finally {
    
            if (null != ossClient){
    
                //  close OSSClient.
                ossClient.shutdown();
            }else if (null != inputStream){
    
                try {
    
                    inputStream.close();
                } catch (IOException e) {
    
                    e.printStackTrace();
                }
            }
        }
    }

    /** *  Delete files in bulk  * 1. Fill in the full path of multiple files to be deleted . * 2. The file full path cannot contain Bucket name . Format :xxxDir/test.png  or  test.png * * @param fileWithPathList * @return  Number of files deleted  */
    public Long deleteBatchObj(List<String> fileWithPathList){
    
        Long count = 0L;
        OSS ossClient = new OSSClientBuilder().build(endPoint,accessKeyId,secret);
        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(fileWithPathList).withEncodingType("url"));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
        for (String obj : deletedObjects) {
    
            try {
    
                String delObjStr = URLDecoder.decode(obj,"UTF-8");
                System.out.println(delObjStr);// Output the deleted file name 
                count++;
            } catch (UnsupportedEncodingException e) {
    
                e.printStackTrace();
            }
        }
        if (null != ossClient){
    
            ossClient.shutdown();
        }
        return count;
    }

}

Four 、demo demonstration

4.1 SpringBoot Start class

@SpringBootApplication
@ComponentScan(basePackages = {
    "com.ccbx.ymjr.base", "com.ccbx.ymjr.oss"})
public class OssServiceAp {
    
    public static void main(String[] args) {
    
        SpringApplication.run(OssServiceAp.class,args);
    }
}

4.2 Controller Interface

/** * @Description * @Author cb * @Date 2022-01-06 11:59 **/
@RestController
@RequestMapping("/api/oos")
@Api(tags = " Operate Alibaba cloud OOS The interface to the server ")
public class OSSController {
    

    @Autowired
    private OSSUtils ossUtils;

    @PostMapping("/upload")
    @ApiOperation(" Upload files to OSS The server ")
    public Result  upload(MultipartFile file){
    
        String url = ossUtils.uploadFileStream(file);
        return Result.ok().data("url",url);
    }

    @PostMapping("/deleteBatchFile")
    @ApiOperation(" Batch deletion OSS Files on the server ")
    public Result deleteBatchFileFromOSS(@RequestBody List<String> filePathList){
    
        try {
    
            Long deleteCount = ossUtils.deleteBatchObj(filePathList);
            return Result.ok().data("deleteCount",deleteCount);
        } catch (Exception e) {
    
            e.printStackTrace();
            return Result.error().message(" Error deleting files in batch ");
        }
    }

}

4.3 swagger test

4.3.1 Upload test



4.3.2 Batch delete test


I'm looking at Bucket The file in has been deleted .

原网站

版权声明
本文为[Slightly drunk CC]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170528546897.html