This is the 26th day of my participation in the August Text Challenge.More challenges in August

Today, I will talk about OSS, and in the next few days, I will sort out some more integration cases with SpringBoot. Application practice, dry goods full.

In the future, there will be several topics, such as concurrent topics, source topics, interviews, etc. (only the dry stuff will be shared). The design project is over. If you are interested, you can click on my profile picture to see the historical article.

Without further ado, let’s get to the point

File processing OSS

In our daily development is usually used to achieve file upload, commonly known as the file server. At the earliest. I have used FastDfs+Nginx to achieve file upload and access.

I wrote a FastDfs+Nginx record earlier this year

CSDN Link: blog.csdn.net/yangning_/a…

With the update and iteration of technology, relying on the development of Ali Cloud ecosystem OSS applications

  • Ali Cloud Object Storage Service (OSS) is a massive, secure, low-cost and highly reliable cloud Storage Service provided by Ali Cloud

  • Data can be uploaded and downloaded at any time, anywhere, and on any Internet device through a simple REST interface. Based on OSS, you can build a variety of multimedia sharing websites, web disks, personal and enterprise data backup services based on large-scale data.

Using OSS premise

You need to create a set of OSS space of your own in ali Cloud background. This section will focus on SpringBoot integration without further details (see the official documentation below)

Official documentation: help.aliyun.com/document_de…

So let’s look at SpringBoot integrating OSS implementation file processing capabilities

OSS SpringBoot integration

You can’t do anything without the first step, Maven

<!-- 图片上传 SDK 阿里云oss -->
  <dependency>
   <groupId>com.aliyun.oss</groupId>
   <artifactId>aliyun-sdk-oss</artifactId>
   <version>3.4.0</version>
  </dependency>
Copy the code

Here is the configuration of YML

aliyun:
  oss:
    # Region node for OSS
    endpoint: http://oss-cn-qingdao.aliyuncs.com
    # accessId = accessId
    accessKeyId: AccessId of Aliyun
    # Ali corresponds to accessKey
    accessKeySecret: The accessKey of Ali Cloud

    # bucketName Specifies the name of the bucket on the OSS
    bucketName: yn-bucket-1
Copy the code

1, oss corresponding region node, click in the OSS list, you can see the bucketName, of course, you can create the environment in advance

2, Ali corresponding (accessId, accessKeySecret) can be seen, Ali cloud background click on the upper right profile picture

Code implementation

OK, once everything is ready, let’s go to the code

/** * Operate oss tool classes *@Date 2021/8/28 11:14 下午
 * @Author yn
 */
@Component
@Configuration
public class AliyunOssUtil {


    @Value("${aliyun.oss.endpoint}")
    private String endpoint;


    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;



    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;


    @Value("${aliyun.oss.bucketName}")
    private String bucketName;




    private OSS ossClient;


    /** * Initializes the OSS instance * singleton *@return* /
    private OSS getInstance(a) {
        // Control concurrency
        if(ossClient==null) {synchronized(AliyunOssUtil.class){
                if(ossClient==null){
                    ossClient = newOSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); }}}return ossClient;
    }



    /** * upload */
    public void  upload(InputStream file, String fileName){
        getInstance().putObject(bucketName,fileName,file);
    }


    /** * delete file *@param fileName
     */
    public void deleteFile(String fileName) {
        OSS ossClient = getInstance();
        try {
            ossClient.deleteObject(bucketName, fileName);
        }
        catch (final Exception e) {
            System.out.println("Failed to delete file, file name ->"+fileName);
        }
        finally {
            // It is guaranteed to be releasedossClient.shutdown(); }}/** * query file image list *@return* /
    public List<OSSObjectSummary> list(a) {
        // Set the maximum number.
        final int maxKeys = 200;
        // List the files.
        ObjectListing objectListing = getInstance().listObjects(new ListObjectsRequest(bucketName).withMaxKeys(maxKeys));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        returnsums; }}Copy the code

Let’s call

@RestController
@RequestMapping
public class UploadController {

    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    /** * File upload */
    @RequestMapping("/upload")
    public String upload(MultipartFile file) {
        try {
                String fileName = file.getOriginalFilename();
                /** * Change the file name and save the file */
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                // Random number prevents duplicate file names
                String uuid = UUID.randomUUID().toString();
                fileName = uuid + suffix;

                /** * enter aliyun */
                aliyunOssUtil.upload(file.getInputStream(),fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return "Failure";
        }
        return "Success"}}Copy the code

Uploaded successfully

conclusion

OK after looking at the above is not particularly simple, omitted a lot of configuration, other official API we can try some other SAO operation

Notice here. Try to name them with random numbers. Otherwise, it will be overwritten and no errors will be reported