一、前期准备
-
点击控制台进入产品主页
-
点击存储
二、创建图片存储空间
空间地区选择最好选择 华东、华北、华南这三个(根据地区不同,等会在代码里面的配置信息也不同,这三个的配置简单)
三、java集成七牛云
- 所需依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.6</version>
<scope>compile</scope>
</dependency>
- 工具类 QiniuUtil
package com.jeeplus.modules.api.util;
import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import java.util.Map;
//TODO 七牛云图片存储
public class QiniuUtil {
// 外链域名
public static String qiniu_url = "外链域名";
// AccessKey
public static String access_key = "AccessKey";
// SecretKey
public static String secret_key = "SecretKey";
// 存储空间名称
public static String bucketName = "存储空间名称";
// 上传文件
public static String uploadQiNiu(byte[] file, String fileName) {
// 构造一个带指定Zone对象的配置了, Zone.zone0() 代表华东区 Zone.zone1() 代表华北区 Zone.zone2() 代表华南区
Configuration cfg = new Configuration(Zone.zone0());
// 其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
// 默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;
Auth auth = Auth.create(access_key, secret_key);
String token = auth.uploadToken(bucketName);
try {
Response response = uploadManager.put(file, fileName, token);
// 解析上传成功的结果
String bodyString = response.bodyString();
Map map = JSON.parseObject(bodyString, Map.class);
String hash = (String) map.get("key");
System.out.println("hash======" + hash);
System.out.println("1111111111");
System.err.println(hash);
System.out.println("url:" + qiniu_url + fileName);
System.err.println("http://" + qiniu_url + "/" + fileName);
return "http://" + qiniu_url + "/" + fileName;
} catch (QiniuException e) {
Response r = e.response;
System.err.println(r.toString());
System.out.println("上传失败");
try {
System.err.println(r.bodyString());
return null;
} catch (QiniuException ex2) {
//ignore
e.printStackTrace();
return null;
}
}
}
}
-
查看秘钥
-
查看外链域名
新注册的用户可以使用七牛云提供的30天临时域名,因为我的过期了,所以这里显示空白,如果不仅仅是为了学习,请配置自定义域名
- 空间存储地域不同,配置不同,详见QiniuUtil.java 第32行注释
四、调用示例
注:七牛云对接及其简单,按照步骤一步一步来即可直接使用