SpringBoot uses Ali OSS to implement file cloud storage

preface

We often used in project to the images or document resources, less in general how the class file when we can exist in the server directly, but if once when I get a certain number of these files if in on the application server will inevitably impact on the performance of the application server, and sometimes these images resources also should be displayed directly in front of, So it’s not appropriate to put it on an application server. Some large Internet companies may use distributed file systems for file storage purposes, but this approach has a high threshold. How to find a suitable and cost-effective way to store files? Then the object storage service OSS has to be mentioned.

FastDFS Distributed File Systems refer to my blog: FastDFS Distributed File Systems

The body of the

Object Storage Service

Object storage Service (OSS) : a massive, secure, low-cost, and highly reliable cloud storage service suitable for storing files of any type:

  • OSSCan be used for pictures, audio and video, log and other mass file storage.
  • Various terminal equipment,WebWebsite applications, mobile applications can be directly toOSSWrite or read data.
  • OSSSupports streaming and file writing.

    In short, we passOSSCan avoid storing a large number of files, images and other resources in the server to increase the serverIORead/write bandwidth of.

SpringBoot uses Ali OSS to implement file cloud storage

preparation

Step 1: InAliyun MallExample Purchase the object storage service

Step 2: InAli Cloud ConsoleconfigurationAccessKey

Code section

Maven rely on

<! --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId> aliyun-sdK-OSS </artifactId> <version>3.5. 0</version> </dependency> <! --apache comment tools--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <! <dependency> <groupId> Commons -fileupload</groupId> <artifactId> Commons -fileupload</artifactId> <version>1.33.</version>
</dependency>
Copy the code

The properties, application of the configuration class

##basic setting
server.port = 8080
server.address =127.0. 01.Remove # file size limit spring. Servlet. Multipart. Max - file - size = 10 MB spring. Servlet. Multipart. Max - request - size = 10 MBCopy the code

Ossmanagerutil. Java: Ali OSS utility class

/** * ali Oss object storage tool class */
public class OssManagerUtil {

    private staticString Endpoint = "PATH to the OSS public network obtained in OSS"; Private static String accessKeyId = "private static String accessKeyId =";
    private static String accessKeySecret = "AccessKeySecret I applied for in Ali Cloud";
    private static String bucket = "The name of the bucket";


    private static OSS client;


    static {
        client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }


    /** * upload image **@paramFileName Specifies the image name, including the folder name and / *@paramLength Indicates the image size *@paramContent Input stream */
    public static String uploadImage(String fileName, long length, InputStream content) {
        uploadBucketImage(bucket, fileName, length, content);
        return "https://" + bucket + "." + endpoint + "/" + fileName;
    }


    /** * Upload file **@paramBucket Storage space name *@paramFileName indicates the fileName (including the folder name and the slash (/)) *@paramLength Indicates the length of the stream *@paramContent Input stream */
    public static void uploadBucketImage(String bucket, String fileName, long length, InputStream content) {
        // Create Metadata to upload Object
        ObjectMetadata meta = new ObjectMetadata();
        // ContentLength must be set
        meta.setContentLength(length);
        / / upload Object.
        client.putObject(bucket, fileName, content, meta);
    }


    /** * delete file **@paramFileName specifies the fileName. The image name includes the folder name and "/" */
    public static boolean delShopImage(String fileName) {
        // Check whether the file exists
        boolean exist = client.doesObjectExist(bucket, fileName);
        // Failed to delete the file
        if(! exist) {return false;
        }
        // Perform the delete
        client.deleteObject(bucket, fileName);
        return true;
    }


    /** * get the url of the uploaded file **@paramFileName indicates the fileName (including the folder name and the slash (/)) *@return* /
    public static String getUrl(String fileName) {
        // Set the URL expiration time to 10 years 3600L * 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        / / generated URL
        URL url = client.generatePresignedUrl(bucket, fileName, expiration);
        if(url ! =null) {
            return url.toString();
        }
        return null;
    }

    /** * Create storage space **@paramBucketName New storage space The default storage type is standard and has the private permission. *@return* /
    public static void crateBucket(String bucketName) {
        // Create storage space The default storage type is standard and private.client.createBucket(bucketName); }}Copy the code

validation

Test interface: file upload

/** * upload the file to ali oss */
@PostMapping("/uploadFiletoOss")
@apiOperation (value = "upload file to Ali oss")
public ResponseResult uploadFiletoOss(@RequestParam("file")MultipartFile file)throws IOException{
    String fileName = file.getOriginalFilename();
    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
    fileName = UUID.randomUUID().toString().replace("-"."") + "." + suffix;
    String url = OssManagerUtil.uploadImage(fileName,file.getInputStream().available(),file.getInputStream());
    return ResponseResult.success(url);
}
Copy the code

Access test interface:

Open the URL of the OSS online file returned by the interface, and obtain the online file:

The source code

The project source code is available from my Github: github source address

See my blog: SpringBoot Templates out of the box for the source code analysis