SpringBoot upload files to seven cattle cloud

Ready to work

maven

pom.xml add seven cattle cloud-sdk-dependent

        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>7.2.27</version>
        </dependency>

Configuration Item

Seven cattle cloud upload the necessary configuration has: accessKey, secretKey, bucket
which accessKey, secretKey can be viewed at the website

https://portal.qiniu.com/user/key

bucket storage space for your name, as follows:
image.png


achieve

application.yml Configuration

upload:
  qiniu:
    domain: 填你的域名
    access-key: 你的accesskey
    secret-key: 你的secretKey
    bucket: 你的存储空间名,我这里为colablog

I can see seven cattle cloud upload configuration has domainthis configuration, the configuration buket seven cattle cloud storage domain, in content management , the success is mainly used for uploading files after the file access path to return back.
image.png
But this is the limit of 30 days using the domain name, so you'd better bind a new domain name.

Upload configuration class

The use SpringBoot @ConfigurationPropertiesand @Componentannotations for configuration upload class UploadProperties,
because there may be local to upload configuration upload and upload cloud upload or other, so I left the class configuration extension point. Because the class has been inspired rabbitmq configuration, and uploading configuration is not a lot, so the internal like to split this configuration category. Upload configuration classes as follows:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author Johnson
 * @date 2019/12/16/ 09:35:36
 */
@Component
@ConfigurationProperties(prefix = "upload")
public class UploadProperties {

    private Local local = new Local();

    public Local getLocal() {
        return local;
    }

    /**
     * @author: Johnson
     * @Date: 2019/12/16
     * 本地上传配置
     */
    public class Local {
        ...
    }

    private Qiniu qiniu = new Qiniu();

    public Qiniu getQiniu() {
        return qiniu;
    }

    /**
     * @author: Johnson
     * @Date: 2019/12/16
     * 七牛云上传配置
     */
    public class Qiniu {
        /**
         * 域名
         */
        private String domain;

        /**
         * 从下面这个地址中获取accessKey和secretKey
         * https://portal.qiniu.com/user/key
         */
        private String accessKey;

        private String secretKey;

        /**
         * 存储空间名
         */
        private String bucket;

        public String getDomain() {
            return domain;
        }

        public void setDomain(String domain) {
            this.domain = domain;
        }

        public String getAccessKey() {
            return accessKey;
        }

        public void setAccessKey(String accessKey) {
            this.accessKey = accessKey;
        }

        public String getSecretKey() {
            return secretKey;
        }

        public void setSecretKey(String secretKey) {
            this.secretKey = secretKey;
        }

        public String getBucket() {
            return bucket;
        }

        public void setBucket(String bucket) {
            this.bucket = bucket;
        }
    }
}

Seven cattle cloud upload interfaces and classes

Upload interfaces as follows:

public interface UploadFile {
    String uploadFile(MultipartFile file);
}

Upload class

import cn.colablog.blogserver.utils.properties.UploadProperties;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author Johnson
 * @date 2019/12/14/ 17:20:16
 * 上传文件到七牛云
 */
public class UploadFileQiniu implements UploadFile {

    private UploadProperties.Qiniu properties;

    //构造一个带指定Region对象的配置类
    private Configuration cfg = new Configuration(Region.region2());

    private UploadManager uploadManager= new UploadManager(cfg);

    public UploadFileQiniu(UploadProperties.Qiniu properties) {
        this.properties = properties;
    }

    /**
    * @author: Johnson
    */
    @Override
    public String uploadFile(MultipartFile file) {
        Auth auth = Auth.create(properties.getAccessKey(), properties.getSecretKey());
        String token = auth.uploadToken(properties.getBucket());
        try {
            String originalFilename = file.getOriginalFilename();
            // 文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileKey = UUID.randomUUID().toString() + suffix;
            Response response = uploadManager.put(file.getInputStream(), fileKey, token, null, null);
            return properties.getDomain() + fileKey;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }
}

RegionConfiguration, where access area on behalf of space, because my storage area of South China. Therefore, in order Region.region2()to see their own storage area can be in the space overview of view to the bottom, there is not a screenshot, image place too.
RegionCorresponding settings:
image.png

Well, preparatory work has been completed, and now to call, call the class as follows:

@RestController
@RequestMapping("/upload")
public class UploadFileController {
    @Autowired
    UploadProperties uploadProperties;

    @PostMapping("/img")
    public String uploadFileYun(MultipartFile file) {
        // 上传到七牛云
        UploadFile uploadFile = new UploadFileQiniu(uploadProperties.getQiniu());
        return uploadFile.uploadFile(file);
    }
}

Is not it simple? Fart ah! A simple wool, in fact, I've simplified, in fact, the structure of my project is complex than this.


to sum up

A: I class names are to Uploadbegin with, the class name has been written is dead only upload function, limiting the scalability of this class, and if add file delete function, should not be added to this class. Now in the reconstruction operation file (non-file upload) of the functional modules.

Two: At first I thought the file upload function that may be used is relatively small, so use the time before going to instantiate the file upload class, but this needs to be determined according to development scenarios, because my project is a blog back office systems, often Photo, the upload file types may be injected into Spring container, it can reduce the overhead of example (though small). The word is injected with @Componentclass notes.

Three: Profiles why I think the use of the internal configuration item class to divide it? In fact, we write some similar functions when other people can go look at the source code reference, of course, here we refer to the source of the great God. Because I'm writing a CI when CI wanted to see how big God is written into the configuration items on the point of rabbitmq. So, ah, I see the code for big God really is the lack of progress.

If you want to see more detailed official document, please click on the link below:

https://developer.qiniu.com/kodo/sdk/1239/java


Finally: thanks for reading, Thanks ♪ (· ω ·) Techno

Personal blog URL: https://colablog.cn/

If my articles help to you, I can focus on the public micro-channel number, the first time to share your article

Micro-channel public number

Guess you like

Origin www.cnblogs.com/Johnson-lin/p/12059067.html