七牛云存储图片

注册七牛云,创建存储空间略。

导入依赖

<!--七牛云存储-->
<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>[7.2.0, 7.2.99]</version>
</dependency>
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.14.2</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>happy-dns-java</artifactId>
    <version>0.1.6</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

QiniuCloudService类

package com.kai.api;

import com.google.gson.Gson;
import com.kai.constant.ActionConstant;
import com.kai.constant.ErrorConstant;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Component
public class QiniuCloudService {

    @Value("${七牛云的ACCESS_KEY}")
    private String ACCESS_KEY;

    @Value("${七牛云的SECRET_KEY}")
    private String SECRET_KEY;

    @Value("${七牛云的空间名}")
    private String BUCKET;

    @Value("${七牛云CDN 加速域名,eg:http://image.xxxxx.com/}")
    public String QINIU_UPLOAD_SITE;

    public String upload(MultipartFile file,String filename){
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);
        try {
            Response response = uploadManager.put(file.getInputStream(),filename,upToken, null);

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet.hash;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ErrorConstant.Action.UPLOAD_FAILED;
    }

    public String delete(String filename){
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        Configuration config = new Configuration(Region.region2());
        BucketManager bucketMgr = new BucketManager(auth, config);

        //指定需要删除的文件,和文件所在的存储空间
        String bucketName = BUCKET;
        String key = filename;
        try {
            bucketMgr.delete(bucketName, key);
            return ActionConstant.Delete.DELETE_SUCCESS;
        } catch (QiniuException e) {
            e.printStackTrace();
            return ErrorConstant.Action.DELETE_FAILED;
        }
    }
}

工具类

七牛云不指定文件名则默认使用文件的hash值作为文件名,此处使用自己生成的随机文件名

//获得指定长度的随机字符串
public static String getRandomString(int length){
    String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    Random random=new Random();
    StringBuffer sb=new StringBuffer();
    for(int i=0;i<length;i++){
        int number=random.nextInt(62);
        sb.append(str.charAt(number));
    }
    return sb.toString();
}
//获得一个包含当日时间的随机文件名
public static String getTodayFileName(){
    String name = getRandomString(20);
    String time = TimeUtils.getNowTimeByFormat("yyyy-MM-dd");
    return time +"/"+ name;
}

controller

    @PostMapping("/upload/pic")
    @ResponseBody
    public JSONObject uploadPid(MultipartFile file){
        String filename = FileUtils.getTodayFileName();
        qiniuCloudService.upload(file,filename);
		
		生成返回前台的json
        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("data", qiniuCloudService.QINIU_UPLOAD_SITE + filename);
        res.put("msg", ActionConstant.Upload.UPLOAD_SUCCESS);
		//将图片信息保存到数据库中
        imageService.addImage(new Image(null,qiniuCloudService.QINIU_UPLOAD_SITE + filename, TimeUtils.getSystemTime()));
        return res;
    }