成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

七牛云java(服務(wù)端)通用工具類

goji / 2212人閱讀

摘要:前言需要安裝插件。而不是通過(guò)圖片標(biāo)簽然后轉(zhuǎn)換后獲取。推薦是一個(gè)基于的完整的獨(dú)立的微服務(wù)。僅僅需要?jiǎng)?chuàng)建相關(guān)數(shù)據(jù)表,修改數(shù)據(jù)庫(kù)的連接信息,你就可以得到一個(gè)微服務(wù)。

前言

需要安裝lombok插件。

功能列表

上傳本地文件

上傳Base64圖片

獲取文件訪問(wèn)地址

上傳MultipartFile

代碼 pom.xml

    com.qiniu
    qiniu-java-sdk
    [7.2.0, 7.2.99]


    org.projectlombok
    lombok
    1.18.2
    provided
qiniu.properties
# 七牛云配置
qiniu.access-key=你的accessKey
qiniu.secret-key=你的secretKey
qiniu.bucket=你的存儲(chǔ)空間名稱
# [{"zone0":"華東"}, {"zone1":"華北"},{"zone2":"華南"},{"zoneNa0":"北美"},{"zoneAs0":""}]
qiniu.zone=zone0
qiniu.domain-of-bucket=外鏈默認(rèn)域名
# 鏈接過(guò)期時(shí)間,單位是秒,3600代表1小時(shí),-1代表永不過(guò)期
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對(duì)象配置錯(cuò)誤!");
            }
        } 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 文件云端存儲(chǔ)的名稱
     * @param override 是否覆蓋同名同位置文件
     * @return
     */
    public static boolean upload(String localFilePath, String key, boolean override){
        //構(gòu)造一個(gè)帶指定Zone對(duì)象的配置類
        Configuration cfg = new Configuration(QiNiuConfig.getInstance().getZone());
        //...其他參數(shù)參考類注釋
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上傳憑證,然后準(zhǔn)備上傳
        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);
            //解析上傳成功的結(jié)果
            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 圖片沒(méi)經(jīng)過(guò)base64處理的原圖字節(jié)大小,獲取文件大小的時(shí)候,切記要通過(guò)文件流的方式獲取。而不是通過(guò)圖片標(biāo)簽然后轉(zhuǎn)換后獲取。
     * @param file64 圖片base64字符串
     * @param key 文件云端存儲(chǔ)的名稱
     * @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);
        //非華東空間需要根據(jù)注意事項(xiàng) 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();
    }

    /**
     * 獲取文件訪問(wèn)地址
     * @param fileName 文件云端存儲(chǔ)的名稱
     * @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) {
        //構(gòu)造一個(gè)帶指定Zone對(duì)象的配置類
        Configuration cfg = new Configuration(QiNiuConfig.getInstance().getZone());
        //...其他參數(shù)參考類注釋
        UploadManager uploadManager = new UploadManager(cfg);

        //把文件轉(zhuǎn)化為字節(jié)數(shù)組
        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());
            }
            //默認(rèn)上傳接口回復(fù)對(duì)象
            DefaultPutRet putRet;
            //進(jìn)行上傳操作,傳入文件的字節(jié)數(shù)組,文件名,上傳空間,得到回復(fù)對(duì)象
            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 七牛返回的文件存儲(chǔ)的地址,可以使用這個(gè)地址加七牛給你提供的前綴訪問(wèn)到這個(gè)視頻。
            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是一個(gè)基于Spring Boot Oauth2的完整的獨(dú)立的Oauth2 Server微服務(wù)。僅僅需要?jiǎng)?chuàng)建相關(guān)數(shù)據(jù)表,修改數(shù)據(jù)庫(kù)的連接信息,你就可以得到一個(gè)Oauth2 Server微服務(wù)。

gitee版本

github版本

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/76748.html

相關(guān)文章

  • XBlog: Vue+Express+Mongodb的全??蓴U(kuò)展的完整博客系統(tǒng)

    摘要:注冊(cè)成功后會(huì)返回注冊(cè)用戶的此就是上面說(shuō)到的,用于用戶登陸的基礎(chǔ),請(qǐng)保管好。 地址 https://github.com/billyhoomm...http://blog.billyhu.com 說(shuō)明(Instructions) 本項(xiàng)目后臺(tái)基于express、mongodb,前臺(tái)基于Vue2.0全家桶、bootstrap、scss預(yù)編譯器以及一眾工具類插件 項(xiàng)目前后臺(tái)代碼在同一個(gè)目錄中...

    Salamander 評(píng)論0 收藏0
  • XBlog: Vue+Express+Mongodb的全??蓴U(kuò)展的完整博客系統(tǒng)

    摘要:注冊(cè)成功后會(huì)返回注冊(cè)用戶的此就是上面說(shuō)到的,用于用戶登陸的基礎(chǔ),請(qǐng)保管好。 地址 https://github.com/billyhoomm...http://blog.billyhu.com 說(shuō)明(Instructions) 本項(xiàng)目后臺(tái)基于express、mongodb,前臺(tái)基于Vue2.0全家桶、bootstrap、scss預(yù)編譯器以及一眾工具類插件 項(xiàng)目前后臺(tái)代碼在同一個(gè)目錄中...

    banana_pi 評(píng)論0 收藏0
  • XBlog: Vue+Express+Mongodb的全??蓴U(kuò)展的完整博客系統(tǒng)

    摘要:注冊(cè)成功后會(huì)返回注冊(cè)用戶的此就是上面說(shuō)到的,用于用戶登陸的基礎(chǔ),請(qǐng)保管好。 地址 https://github.com/billyhoomm...http://blog.billyhu.com 說(shuō)明(Instructions) 本項(xiàng)目后臺(tái)基于express、mongodb,前臺(tái)基于Vue2.0全家桶、bootstrap、scss預(yù)編譯器以及一眾工具類插件 項(xiàng)目前后臺(tái)代碼在同一個(gè)目錄中...

    fizz 評(píng)論0 收藏0
  • 牛云趙之?。憾嗑S度融合賦能視頻 AI 的實(shí)踐

    摘要:月日下午,趙之健在七牛架構(gòu)師實(shí)踐日第二十九期進(jìn)行了多維度融合賦能視頻的實(shí)踐為題的實(shí)戰(zhàn)分享。本文主要分享了七牛人工智能實(shí)驗(yàn)室在視頻方面的一些工作,分別有兩個(gè)關(guān)鍵詞一個(gè)是多維度融合,另外一個(gè)關(guān)鍵詞是視頻。 6 月 30 日下午,趙之健在七牛架構(gòu)師實(shí)踐日第二十九期進(jìn)行了《多維度融合賦能視頻 AI 的實(shí)踐》為題的實(shí)戰(zhàn)分享。? 作者簡(jiǎn)介:?showImg(https://segmentfault...

    Taonce 評(píng)論0 收藏0
  • 聊聊畢業(yè)設(shè)計(jì)系列 --- 系統(tǒng)實(shí)現(xiàn)

    摘要:七牛云接入本系統(tǒng)的圖片,音視頻是放在七牛云,所以需要接入七牛云。在服務(wù)端通過(guò)接口請(qǐng)求來(lái)獲取七牛云上傳,客戶端獲取到七牛云,通過(guò)不同方案將帶上。 效果展示 showImg(https://user-gold-cdn.xitu.io/2018/8/26/16576a709bd02f5f?w=1409&h=521&f=gif&s=30128195); showImg(https://user...

    null1145 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<