springboot integrates oss to upload, view, delete and download files

Keywords: Java Spring Lombok Apache

springboot integrates oss to upload, view, delete and download files

1. What is Object Storage OSS?

Answer: Aliyun Object Storage Service (OSS) is a massive, secure, low-cost and highly reliable cloud storage service provided by Aliyun. Its data design persistence is not less than 99.999999% (129), and service design availability (or business continuity) is not less than 99.995%.

OSS has a platform-independent RESTful API interface that allows you to store and access any type of data in any application, at any time, anywhere.

You can easily move massive data into or out of Aliyun OSS using API, SDK interface or OSS migration tools provided by Aliyun. After the data is stored in Aliyun OSS, you can choose Standard as the main storage mode for mobile applications, large websites, photo sharing or hot audio and video, or Infrequent Access and Archive with lower cost and longer storage period. Frequent access to data storage.

For more information about oss, please refer to Aliyun OSs Object Storage Official Documents address

2. Log on to Aliyun and enter the console.

Console address

3. Create Bucket

Click OK, so we can build it.

Now let's start coding (1)

Create a new spring boot project

Import the following dependencies

pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.9</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>

application.properties configuration file



accessKeyId and accessKeySecret need to be checked in accesskeys

Write a configuration file, AliyunConfig.class

package com.tuanzi.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
 * @desc
 *
 * @author Dumpling
 * @date 2019-07-31 11:31
 */
@Configuration
@PropertySource(value = {"classpath:application.properties"})
@ConfigurationProperties(prefix = "aliyun")
@Data
public class AliyunConfig {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String urlPrefix;

    @Bean
    public OSS oSSClient() {
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }
}

controller class

package com.tuanzi.controller;

import com.tuanzi.service.FileUploadService;
import com.tuanzi.vo.FileUploadResult;
import com.aliyun.oss.model.OSSObjectSummary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author Dumpling
 * @desc
 * @date 2019-07-31 11:31
 */
@Controller
public class FileUploadController {
    @Autowired
    private FileUploadService fileUploadService;

    /**
     * @author Dumpling
     * @desc File upload to oss
     * @return FileUploadResult
     * @Param uploadFile
     */
    @RequestMapping("file/upload")
    @ResponseBody
    public FileUploadResult upload(@RequestParam("file") MultipartFile uploadFile)
            throws Exception {
        return this.fileUploadService.upload(uploadFile);
    }

    /**
     * @return FileUploadResult
     * @desc Delete files on oss according to file name
     * @author Dumpling
     * @Param objectName
     */
    @RequestMapping("file/delete")
    @ResponseBody
    public FileUploadResult delete(@RequestParam("fileName") String objectName)
            throws Exception {
        return this.fileUploadService.delete(objectName);
    }

    /**
     * @author Dumpling
     * @desc Query all files on oss
     * @return List<OSSObjectSummary>
     * @Param
     */
    @RequestMapping("file/list")
    @ResponseBody
    public List<OSSObjectSummary> list()
            throws Exception {
        return this.fileUploadService.list();
    }

    /**
     * @author Dumpling
     * @desc Download files on oss according to file name
     * @return
     * @Param objectName
     */
    @RequestMapping("file/download")
    @ResponseBody
    public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
        //Notify the browser to download as an attachment
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));
        this.fileUploadService.exportOssFile(response.getOutputStream(),objectName);
    }
}

service

package com.tuanzi.service;

import com.tuanzi.config.AliyunConfig;
import com.tuanzi.vo.FileUploadResult;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;

/**
 * @author Dumpling
 * @desc
 * @date 2019-07-31 11:31
 */
@Service
public class FileUploadService {
    // Format to allow upload
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};
    @Autowired
    private OSS ossClient;
    @Autowired
    private AliyunConfig aliyunConfig;

    /**
     * @author Dumpling
     * @desc File upload
     * @date 2019-07-31 11:31
     */
    public FileUploadResult upload(MultipartFile uploadFile) {
        // Check picture format
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
                    type)) {
                isLegal = true;
                break;
            }
        }
        //Encapsulate Result objects and place byte arrays of files into result objects
        FileUploadResult fileUploadResult = new FileUploadResult();
        if (!isLegal) {
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        //New file path
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        // Upload to Aliyun
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new
                    ByteArrayInputStream(uploadFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //Upload failure
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        fileUploadResult.setStatus("done");
        fileUploadResult.setResponse("success");
        fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }

    /**
     * @author Dumpling
     * @desc Generate paths and file names such as: //images/2019/08/10/15564277465972939.jpg
     * @date 2019-07-31 11:31
     */
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

    /**
     * @author Dumpling
     * @desc View the list of files
     * @date 2019-07-31 11:31
     */
    public List<OSSObjectSummary> list() {
        // Set the maximum number.
        final int maxKeys = 200;
        // List the documents.
        ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        return sums;
    }

    /**
     * @author Dumpling
     * @desc Delete files
     * @date 2019-07-31 11:31
     */
    public FileUploadResult delete(String objectName) {
        // According to BucketName,objectName deletes files
        ossClient.deleteObject(aliyunConfig.getBucketName(), objectName);
        FileUploadResult fileUploadResult = new FileUploadResult();
        fileUploadResult.setName(objectName);
        fileUploadResult.setStatus("removed");
        fileUploadResult.setResponse("success");
        return fileUploadResult;
    }

    /**
     * @author Dumpling
     * @desc Download files
     * @date 2019-07-31 11:31
     */
    public void exportOssFile(OutputStream os, String objectName) throws IOException {
        // ossObject contains the name of the storage space where the file is located, the name of the file, the meta-information of the file and an input stream.
        OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);
        // Read the contents of the file.
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        BufferedOutputStream out = new BufferedOutputStream(os);
        byte[] buffer = new byte[1024];
        int lenght = 0;
        while ((lenght = in.read(buffer)) != -1) {
            out.write(buffer, 0, lenght);
        }
        if (out != null) {
            out.flush();
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
}

Return value class

package com.tuanzi.vo;

import lombok.Data;

/**
 * @author Dumpling
 * @desc Return value
 * @date 2019-07-31 11:31
 */
@Data
public class FileUploadResult {
    // File Unique Identification
    private String uid;
    // file name
    private String name;
    // The status is: uploading done error removed
    private String status;
    // Server-side response content, such as:'{status: `success'}'
    private String response;
}

That's it.
Let's run the project.
See the effect: Visit http://localhost:8080/upload.html

Let's upload an image that doesn't conform to the format. There will be a hint.

To upload a match

Upload success will be displayed directly. Let's see if oss has any pictures we uploaded

It was found that there were also
Next, let's test queries, downloads, and deletions.
Visit: http://localhost:8080/manager.html

You will see the pictures we uploaded.
Here's a simple example.
Download pictures

Delete pictures

Take a look inside oss

It has been deleted!!!

Posted by smurl on Sat, 10 Aug 2019 07:07:28 -0700