资讯专栏INFORMATION COLUMN

七牛云java(服务端)通用工具类

goji / 1981人阅读

摘要:前言需要安装插件。而不是通过图片标签然后转换后获取。推荐是一个基于的完整的独立的微服务。仅仅需要创建相关数据表,修改数据库的连接信息,你就可以得到一个微服务。

前言

需要安装lombok插件。

功能列表

上传本地文件

上传Base64图片

获取文件访问地址

上传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=你的存储空间名称
# [{"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版本

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/76748.html

相关文章

  • XBlog: Vue+Express+Mongodb的全栈可扩展的完整博客系统

    摘要:注册成功后会返回注册用户的此就是上面说到的,用于用户登陆的基础,请保管好。 地址 https://github.com/billyhoomm...http://blog.billyhu.com 说明(Instructions) 本项目后台基于express、mongodb,前台基于Vue2.0全家桶、bootstrap、scss预编译器以及一众工具类插件 项目前后台代码在同一个目录中...

    Salamander 评论0 收藏0
  • XBlog: Vue+Express+Mongodb的全栈可扩展的完整博客系统

    摘要:注册成功后会返回注册用户的此就是上面说到的,用于用户登陆的基础,请保管好。 地址 https://github.com/billyhoomm...http://blog.billyhu.com 说明(Instructions) 本项目后台基于express、mongodb,前台基于Vue2.0全家桶、bootstrap、scss预编译器以及一众工具类插件 项目前后台代码在同一个目录中...

    banana_pi 评论0 收藏0
  • XBlog: Vue+Express+Mongodb的全栈可扩展的完整博客系统

    摘要:注册成功后会返回注册用户的此就是上面说到的,用于用户登陆的基础,请保管好。 地址 https://github.com/billyhoomm...http://blog.billyhu.com 说明(Instructions) 本项目后台基于express、mongodb,前台基于Vue2.0全家桶、bootstrap、scss预编译器以及一众工具类插件 项目前后台代码在同一个目录中...

    fizz 评论0 收藏0
  • 牛云赵之健:多维度融合赋能视频 AI 的实践

    摘要:月日下午,赵之健在七牛架构师实践日第二十九期进行了多维度融合赋能视频的实践为题的实战分享。本文主要分享了七牛人工智能实验室在视频方面的一些工作,分别有两个关键词一个是多维度融合,另外一个关键词是视频。 6 月 30 日下午,赵之健在七牛架构师实践日第二十九期进行了《多维度融合赋能视频 AI 的实践》为题的实战分享。
 作者简介:
showImg(https://segmentfault...

    Taonce 评论0 收藏0
  • 聊聊毕业设计系列 --- 系统实现

    摘要:七牛云接入本系统的图片,音视频是放在七牛云,所以需要接入七牛云。在服务端通过接口请求来获取七牛云上传,客户端获取到七牛云,通过不同方案将带上。 效果展示 showImg(https://user-gold-cdn.xitu.io/2018/8/26/16576a709bd02f5f?w=1409&h=521&f=gif&s=30128195); showImg(https://user...

    null1145 评论0 收藏0

发表评论

0条评论

goji

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<