1. 程式人生 > >七牛雲java(服務端)通用工具類

七牛雲java(服務端)通用工具類

前言

需要安裝lombok外掛。

功能列表

  • 上傳本地檔案
  • 上傳Base64圖片
  • 獲取檔案訪問地址
  • 上傳MultipartFile

程式碼

pom.xml

<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>[7.2.0, 7.2.99]</version>
</dependency>
<dependency
>
<groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.2</version> <scope>provided</scope> </dependency>

qiniu.properties

# 七牛雲配置
qiniu.access-key=你的accessKey
qiniu.secret-key=你的secretKey
qiniu.bucket=你的儲存空間名稱
# 
[{'zone0':'華東'}, {'zone1':'華北'},{'zone2':'華南'},{'zoneNa0':'北美'},{'zoneAs0':''}] qiniu.zone=zone0 qiniu.domain-of-bucket=外鏈預設域名 # 連結過期時間,單位是秒,3600代表1小時,-1代表永不過期 qiniu.expire-in-seconds=-1

QiNiuConfig.java

import com.qiniu.common.Zone;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Properties;

/**
 * 七牛雲配置
 *
 * @author
simon * @create 2018-08-15 10:44 **/
@Slf4j @Data public class QiNiuConfig { private String accessKey; private String secretKey; private String bucket; private Zone zone; private String domainOfBucket; private long expireInSeconds; private static QiNiuConfig instance = new QiNiuConfig(); private QiNiuConfig(){ Properties prop = new Properties(); try { prop.load(QiNiuConfig.class.getResourceAsStream("/qiniu.properties")); accessKey = prop.getProperty("qiniu.access-key"); secretKey = prop.getProperty("qiniu.secret-key"); bucket = prop.getProperty("qiniu.bucket"); domainOfBucket = prop.getProperty("qiniu.domain-of-bucket"); expireInSeconds = Long.parseLong(prop.getProperty("qiniu.expire-in-seconds")); String zoneName = prop.getProperty("qiniu.zone"); if(zoneName.equals("zone0")){ zone = Zone.zone0(); }else if(zoneName.equals("zone1")){ zone = Zone.zone1(); }else if(zoneName.equals("zone2")){ zone = Zone.zone2(); }else if(zoneName.equals("zoneNa0")){ zone = Zone.zoneNa0(); }else if(zoneName.equals("zoneAs0")){ zone = Zone.zoneAs0(); }else{ throw new Exception("Zone物件配置錯誤!"); } } catch (Exception e) { e.printStackTrace(); } } public static QiNiuConfig getInstance(){ return instance; } public static void main(String[] args) { System.out.println(QiNiuConfig.getInstance().getAccessKey()); } }

QiNiuUtil.java

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.UrlSafeBase64;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 七牛上傳下載工具類
 *
 * @author simon
 * @create 2018-08-15 11:21
 **/
@Slf4j
public class QiNiuUtil {
    /**
     * 上傳本地檔案
     * @param localFilePath 本地檔案完整路徑
     * @param key 檔案雲端儲存的名稱
     * @param override 是否覆蓋同名同位置檔案
     * @return
     */
    public static boolean upload(String localFilePath, String key, boolean override){
        //構造一個帶指定Zone物件的配置類
        Configuration cfg = new Configuration(QiNiuConfig.getInstance().getZone());
        //...其他引數參考類註釋
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上傳憑證,然後準備上傳
        Auth auth = Auth.create(QiNiuConfig.getInstance().getAccessKey(), QiNiuConfig.getInstance().getSecretKey());
        String upToken;
        if(override){
            upToken = auth.uploadToken(QiNiuConfig.getInstance().getBucket(), key);//覆蓋上傳憑證
        }else{
            upToken = auth.uploadToken(QiNiuConfig.getInstance().getBucket());
        }
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上傳成功的結果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return true;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
                return false;
            }
            return false;
        }
    }

    /**
     * 上傳Base64圖片
     * @param l 圖片沒經過base64處理的原圖位元組大小,獲取檔案大小的時候,切記要通過檔案流的方式獲取。而不是通過圖片標籤然後轉換後獲取。
     * @param file64 圖片base64字串
     * @param key 檔案雲端儲存的名稱
     * @param override 是否覆蓋同名同位置檔案
     * @return
     * @throws IOException
     */
    public static boolean uploadBase64(int l, String file64, String key, boolean override) throws IOException{
        /*FileInputStream fis = null;
        int l = (int) (new File(localFilePath).length());
        byte[] src = new byte[l];
        try {
            fis = new FileInputStream(new File(localFilePath));
            fis.read(src);
        }catch (FileNotFoundException e){
            e.printStackTrace();
            log.error(e.getMessage());
            log.error("圖片檔案讀取失敗");
            return false;
        }
        String file64 = Base64.encodeToString(src, 0);*/

        Auth auth = getAuth();
        String upToken;
        if(override){
            upToken = auth.uploadToken(QiNiuConfig.getInstance().getBucket(), key);//覆蓋上傳憑證
        }else{
            upToken = auth.uploadToken(QiNiuConfig.getInstance().getBucket());
        }

        String url = "http://upload.qiniup.com/putb64/" + l+"/key/"+ UrlSafeBase64.encodeToString(key);
        //非華東空間需要根據注意事項 1 修改上傳域名
        RequestBody rb = RequestBody.create(null, file64);
        Request request = new Request.Builder().
                url(url).
                addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + upToken)
                .post(rb).build();
        //System.out.println(request.headers());
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = client.newCall(request).execute();
        //System.out.println(response);
        return response.isSuccessful();
    }

    /**
     * 獲取檔案訪問地址
     * @param fileName 檔案雲端儲存的名稱
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String fileUrl(String fileName) throws UnsupportedEncodingException {
        String encodedFileName = URLEncoder.encode(fileName, "utf-8");
        String publicUrl = String.format("%s/%s", QiNiuConfig.getInstance().getDomainOfBucket(), encodedFileName);
        Auth auth = getAuth();
        long expireInSeconds = QiNiuConfig.getInstance().getExpireInSeconds();
        if(-1 == expireInSeconds){
            return auth.privateDownloadUrl(publicUrl);
        }
        return auth.privateDownloadUrl(publicUrl, expireInSeconds);
    }

    /**
     * 上傳MultipartFile
     * @param file
     * @param key
     * @param override
     * @return
     * @throws IOException
     */
    public static boolean uploadMultipartFile(MultipartFile file, String key, boolean override) {
        //構造一個帶指定Zone物件的配置類
        Configuration cfg = new Configuration(QiNiuConfig.getInstance().getZone());
        //...其他引數參考類註釋
        UploadManager uploadManager = new UploadManager(cfg);

        //把檔案轉化為位元組陣列
        InputStream is = null;
        ByteArrayOutputStream bos = null;

        try {
            is = file.getInputStream();
            bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int len = -1;
            while ((len = is.read(b)) != -1){
                bos.write(b, 0, len);
            }
            byte[] uploadBytes= bos.toByteArray();

            Auth auth = getAuth();
            String upToken;
            if(override){
                upToken = auth.uploadToken(QiNiuConfig.getInstance().getBucket(), key);//覆蓋上傳憑證
            }else{
                upToken = auth.uploadToken(QiNiuConfig.getInstance().getBucket());
            }
            //預設上傳介面回覆物件
            DefaultPutRet putRet;
            //進行上傳操作,傳入檔案的位元組陣列,檔名,上傳空間,得到回覆物件
            Response response = uploadManager.put(uploadBytes, key, upToken);
            putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);//key 檔名
            System.out.println(putRet.hash);//hash 七牛返回的檔案儲存的地址,可以使用這個地址加七牛給你提供的字首訪問到這個視訊。
            return true;
        }catch (QiniuException e){
            e.printStackTrace();
            return false;
        }catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static Auth getAuth(){
        Auth auth = Auth.create(QiNiuConfig.getInstance().getAccessKey(), QiNiuConfig.getInstance().getSecretKey());
        return auth;
    }
}

推薦

oauthserver是一個基於Spring Boot Oauth2的完整的獨立的Oauth2 Server微服務。僅僅需要建立相關資料表,修改資料庫的連線資訊,你就可以得到一個Oauth2 Server微服務。
- gitee版本
- github版本