七牛云入门使用步骤(图片服务器使用)

登入七牛云官网得到3个比较重要的参数。
如图
1.sk
2.ak
3.测试域名
七牛云入门使用步骤(图片服务器使用)_第1张图片

七牛云入门使用步骤(图片服务器使用)_第2张图片

第一步导入七牛云sdk


        <dependency>
            <groupId>com.qiniugroupId>
            <artifactId>qiniu-java-sdkartifactId>
            <version>7.2.2version>
        dependency>

第二步配置文件

#填写自己的参数
qiniu.accesskey=7hLXQfZfPQPB7EWOrwvgKPLQ8BcskSXC2F3G8HdO
qiniu.secretkey=DtR4cFQ48nAZMANHs3002_q5nKSTgXIXTREyKYnL
qiniu.bucket=oc-bucket
qiniu.cdns=ozgcusern.bkt.clouddn.com

第三步基础工具类以及封装七牛云图片sdk

FileType.java
/**
 * 定义文件类型及其对应魔数
 */
public enum FileType {
    JPEG("FFD8FF"),
    PNG("89504E47"),

    GIF("47494638");

    private String value = "";

    private FileType(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}
FileTypeHelper.java
import java.util.Arrays;
import org.springframework.util.Assert;

public class FileTypeHelper {

    public static FileType getType(byte[] buff){
        Assert.isTrue(buff!=null &&buff.length>28);
        byte[] bytes= Arrays.copyOfRange(buff, 0, 28);
        String magic = bytesToHex(bytes);

        for(FileType type:FileType.values()){
            if(magic.startsWith(type.getValue())) return type;
        }
        return null;
    }

    /**
     * 判断是否为图片,是图片返回true,否则返回false
     * 
     * @param buff
     * @return 图片返回true,否则返回false
     */
    public static boolean isImage(byte[] buff){
        FileType type = getType(buff);
        return FileType.JPEG.equals(type)||FileType.PNG.equals(type);
    }

    private static String bytesToHex(byte[] src) {  
        StringBuilder stringBuilder = new StringBuilder();  
        if (src == null || src.length <= 0) return null;  
        for (int i = 0; i < src.length; i++) {  
            int v = src[i] & 0xFF;  
            String hv = Integer.toHexString(v);  
            if (hv.length() < 2) {  
            stringBuilder.append(0);  
            }  
            stringBuilder.append(hv);  
        }  
        return stringBuilder.toString().toUpperCase();  
    } 

}

QiniuImg.java

/**
 * 七牛图片类
 */
public class QiniuImg implements Serializable{
    private static final long serialVersionUID = -68217983332179128L;

    private String key;//七牛返回的key
    private String url;//原图片的url

    private String url16;//
    private String url32;//
    private String url48;//
    private String url64;//
    private String url128;//
    private String url256;//
    private String url512;//


    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }

    public String getUrl() {
        if(StringUtils.isEmpty(key)) return  null;
        if(this.url==null){
            this.url = QiniuWrapper.getUrl(key);
        }
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }


    public String getUrl16() {
        if(StringUtils.isEmpty(key)) return  null;
        if(this.url16==null){
            this.url16 = QiniuWrapper.getUrl(key, ThumbModel.THUMB_16.getValue());
        }
        return this.url16;
    }
    public void setUrl16(String url16) {
        this.url16 = url16;
    }


    public String getUrl32() {
        if(StringUtils.isEmpty(key)) return  null;
        if(this.url32==null){
            this.url32 = QiniuWrapper.getUrl(key, ThumbModel.THUMB_32.getValue());
        }
        return this.url32;
    }
    public void setUrl32(String url32) {
        this.url32 = url32;
    }


    public String getUrl48() {
        if(StringUtils.isEmpty(key)) return  null;
        if(this.url48==null){
            this.url48 = QiniuWrapper.getUrl(key, ThumbModel.THUMB_48.getValue());
        }
        return this.url48;
    }
    public void setUrl48(String url48) {
        this.url48 = url48;
    }


    public String getUrl64() {
        if(StringUtils.isEmpty(key)) return  null;
        if(this.url64==null){
            this.url64 = QiniuWrapper.getUrl(key, ThumbModel.THUMB_64.getValue());
        }
        return this.url64;
    }
    public void setUrl64(String url64) {
        this.url64 = url64;
    }


    public String getUrl128() {
        if(StringUtils.isEmpty(key)) return  null;
        if(this.url128==null){
            this.url128 = QiniuWrapper.getUrl(key, ThumbModel.THUMB_128.getValue());
        }
        return this.url128;
    }
    public void setUrl128(String url128) {
        this.url128 = url128;
    }


    public String getUrl256() {
        if(StringUtils.isEmpty(key)) return  null;
        if(this.url256==null){
            this.url256 = QiniuWrapper.getUrl(key, ThumbModel.THUMB_256.getValue());
        }
        return this.url256;
    }
    public void setUrl256(String url256) {
        this.url256 = url256;
    }


    public String getUrl512() {
        if(StringUtils.isEmpty(key)) return  null;
        if(this.url512==null){
            this.url512 = QiniuWrapper.getUrl(key, ThumbModel.THUMB_512.getValue());
        }
        return this.url512;
    }
    public void setUrl512(String url512) {
        this.url512 = url512;
    }

    //七牛上传key,然后七牛会返回一个key,将返回的key保存到数据库
    public String getUploadKey(){
        return QiniuKeyGenerator.generateKey();
    }

}

QiniuKeyGenerator.java

/**
 * 资源在七牛云存储的key生成器
 * 注:资源是七牛云存储服务中的逻辑存储单元。对于每一个账号,
 * 该账号里存放的每个资源都有唯一的一对属主空间(Bucket)与键名(Key),作为识别标识
 */
public class QiniuKeyGenerator {

    public static final String KEY = "/{0}/{1}/{2}/{3}";// 多图片可以按照:/表名/字段名/业务值(refId)/时间戳 处理

    public static String generateKey(){
        return MessageFormat.format(KEY, "default", "all", "0", CommonUtil.getUID());
    }

}

QiniuStorage.java

/**
 * 七牛云存储管理器
 * 上传图像和查看图像
 */
public class QiniuStorage {

    /**
     * 上传单张图片;返回上传图片的key
     * @param buff
     */
    public static String uploadImage(byte[] buff){
        String key = QiniuKeyGenerator.generateKey();
        key = QiniuWrapper.upload(buff, key,false);
        return key;
    }

    /**
     * 上传单张图片;返回上传图片的url,此url会过期,切记不要存储在数据库中;
     * @param buff
     * @param img
     * @return QiniuImg
     */
    public static QiniuImg uploadImage(byte[] buff,QiniuImg img){
        String key = QiniuWrapper.upload(buff, img.getUploadKey(),false);
        img.setKey(key);
        return img;
    }


    /**
     * 上传多个图片
     * @param imageBuffs 图片字节数组
     * @param img 分组图片的属性
     * @return
     */
    public static QiniuImg[] uploadImages(byte[][] imageBuffs,QiniuImg img){
        QiniuImg[] images = new QiniuImg[imageBuffs.length];
        for(int i = 0; i < imageBuffs.length; i++){
            QiniuImg newImg = new QiniuImg();
            uploadImage(imageBuffs[i],img);
            newImg.setKey(img.getKey());
            images[i] = newImg;
        }
        return images;
    }


    /**
     * 获取图片链接
     * @param key
     * @return
     */
    public static String getUrl(String key){
        return QiniuWrapper.getUrl(key);
    }

    /**
     * 获取有有效期的图片链接
     * @param key
     * @param expires 单位:秒
     * @return
     */
    public static String getUrl(String key,long expires){
        return QiniuWrapper.getUrl(key,expires);
    }


    /**
     * 获取图片链接
     * @param key
     * @return
     */
    public static String getUrl(String key,ThumbModel model){
        return QiniuWrapper.getUrl(key,model.getValue());
    }

    /**
     * 获取有有效期的图片链接
     * @param key
     * @param expires 单位:秒
     * @return
     */
    public static String getUrl(String key,ThumbModel model,long expires){
        return QiniuWrapper.getUrl(key,model.getValue(),expires);
    }

}

ThumbModel.java

/**
 * 文件的缩略图及其模式字符串定义
 */
public enum ThumbModel {

    THUMB_16("imageView2/2/w/16/h/16"),
    THUMB_32("imageView2/2/w/32/h/32"),
    THUMB_48("imageView2/2/w/48/h/48"),
    THUMB_64("imageView2/2/w/64/h/64"),
    THUMB_128("imageView2/2/w/128/h/128"),
    THUMB_256("imageView2/2/w/256/h/256"),
    THUMB_512("imageView2/2/w/512/h/512");


    private String value;

    private ThumbModel(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

}

七牛云SDK的封装

/**
 * 七牛SDK的包装类,以便于业务使用
 */
public class QiniuWrapper {

    private static final Logger logger = LoggerFactory.getLogger(QiniuWrapper.class);

    private static final String CONFIG_BUCKET="qiniu.bucket";

    private static final String CONFIG_AK="qiniu.accesskey";
    private static final String CONFIG_SK="qiniu.secretkey";
    private static final String CONFIG_CDN="qiniu.cdns";

    private static final Auth auth;
    private static final UploadManager uploadManager;

    private static final String bucketName;
    private static final List cdns;

    /**
     * 从外部文件中初始化七牛存储相关的配置信息
     */
    static{
        Properties properties =PropertiesUtil.getDefaultProperties();
        auth = Auth.create(properties.getProperty(CONFIG_AK), properties.getProperty(CONFIG_SK));
        Configuration cfg = new Configuration(Zone.zone2());//设置空间上传域名
        uploadManager = new UploadManager(cfg);
        bucketName=properties.getProperty(CONFIG_BUCKET);
        String cdn = properties.getProperty(CONFIG_CDN);
        cdns = Arrays.asList(cdn.split(","));
    }

    /**
     * 获取上传资源的token
     * @return
     */
    public static String getUploadToken(){
        return auth.uploadToken(bucketName);
    }

    /**
     * 获取更新资源的token,只能用于更新参数key所代表的资源
     * @param key 存储空间中已存在的资源key
     * @return
     */
    public static String getUploadToken(String key){
        return auth.uploadToken(bucketName,key);
    }

    /**
     * 上传文件
     * @param data 二进制格式的文件内容
     * @param key 文件在七牛中的key
     * @param update 是否是更新
     * @return
     */
    public static String upload(byte[] data,String key,boolean update){
        try {
            String token = update?auth.uploadToken(bucketName,key):auth.uploadToken(bucketName);
            Response response = uploadManager.put(data, getFullKey(data, key), token);
            DefaultPutRet ret = response.jsonToObject(DefaultPutRet.class);
            return ret.key;
        } catch (QiniuException e) {
            logger.error("upload file to qiniu cloud storage failed",e);
        }
        return null;
    }

    private static String getFullKey(byte[] data,String key){
        FileType type= FileTypeHelper.getType(data);
        if(type!=null){
            return key+"."+type.name().toLowerCase();
        }else{
            return key;
        }
    }

    public static String getUrl(String key,String model){
        return getUrl(key, model, 3600);
    }

    /**
     * 获取多个key图片;
     * @param keys 逗号隔开的多个key;
     * @param model
     * @return
     */
    public static List getUrls(String keys,String model){
        List list = null;
        if (org.apache.commons.lang.StringUtils.isNotBlank(keys)) {
            list = new ArrayList();
            for (String key : keys.split(",")) {
                list.add(getUrl(key, model, 3600));
            }
        }
        return list;
    }

    public static String getUrl(String key){
        if(!StringUtils.isEmpty(key)){
            return auth.privateDownloadUrl("http://"+getCDN()+"/@"+key);
        }
        return null;
    }

    /**
     * @param key
     * @param expires 单位:秒
     * @return
     */
    public static String getUrl(String key,long expires){
        if(!StringUtils.isEmpty(key)){
            long time = System.currentTimeMillis()/1000+expires;
            return auth.privateDownloadUrl("http://"+getCDN()+"/@"+key,time);
        }
        return null;
    }

=======================================================
配置文件读取类

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesUtil {

    private static Map propMap = new HashMap();

    /*设置默认的properties文件,方便操作*/
    public static final String DEFAULT_PROPERTIES_FILE="application.properties";

    public static Object getProperty(String file,String key){
        Properties prop = getProperties(file);
        if(prop != null && prop.get(key) != null){
            return prop.get(key);
        }
        return null;
    }

    public static Properties getProperties(String file){
        try {
            if(propMap.get(file) == null){
                Properties prop = new Properties();      
                prop.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(file));
                propMap.put(file,prop);
                return prop;
            }else{
                return propMap.get(file);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void updateProperties(Properties prop,String filePath){

        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            URI fileUri = PropertiesUtil.class.getClassLoader().getResource(filePath).toURI();
            File file = new File(fileUri);

            Properties tmpProp = new Properties();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            tmpProp.load(bis);

            FileOutputStream fos = new FileOutputStream(file);
            for(Object key : prop.keySet()){
                tmpProp.setProperty(String.valueOf(key),String.valueOf(prop.get(key)));
            }
            tmpProp.store(fos, null);
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从默认配置文件中获取properties
     * @return
     */
    public static Properties getDefaultProperties(){
        return getProperties(DEFAULT_PROPERTIES_FILE);
    }

    /**
     * 从默认配置文件中获取配置项
     * @param key
     * @return
     */
    public static String getProperty(String key){
        Properties prop = getDefaultProperties();
        if(prop != null && prop.get(key) != null){
            return prop.getProperty(key);
        }
        return null;
    }

}

第三步测试类进行测试

public class QiNiuTest extends TestCase {
    Logger log = Logger.getLogger(AppTest.class);

    public void testImages() {
        //测试上传图片
        byte[] buff = CommonUtil.getFileBytes(new File("C:/Users/paperpass/Desktop/tu29253_9.jpg"));
        String key = QiniuStorage.uploadImage(buff);
        System.out.println("key = " + key);

        //String key = "/default/all/0/0755ffd19e3e416db0a69ca3b23d744a.jpeg";
        //测试下载图片
        String url = QiniuStorage.getUrl(key);
        System.out.println("url = " + url);

        //测试下载不同大小的图片
        url = QiniuStorage.getUrl(key,ThumbModel.THUMB_256);
        System.out.println("url = " + url);

    }
}

测试结果为


key = /default/all/0/b6a6d44d81f8410ba98b2fa63a9eb62e.jpeg 

url = http://ozgcuyern.bkt.clouddn.com/@/default/all/0/b6a6d44d81f8410ba98b2fa63a9eb62e.jpeg?e=1510896997&token=7hLXQfZfPQPB7EWOrwvgKPLQ8B3skSXC2F3G8HdO:FQc-sMEM-u1TPMZ5qmvsQG0aYDM= 

url = http://ozgcuyern.bkt.clouddn.com/@/default/all/0/b6a6d44d81f8410ba98b2fa63a9eb62e.jpeg?imageView2/2/w/256/h/256&e=1510896997&token=7hLXQfZfPQPB7EWOrwvgKPLQ8B3skSXC2F3G8HdO:1nZqpHb15OV2H5Hb4_7HP_SbEek

数据库中直接保存key的值。通过key可以查到七牛云所在的图片。url中参数e指的图片存储的时间,参数token是前面url的加密之后的字符串

你可能感兴趣的:(淘淘商城)