目录
一、七牛云入门测试
1、注册七牛云账号,完成后选择对象存储
2、在里面创建空间,一个空间相当于一个文件夹,就是将对象上传到的地方
3、查看个人秘钥,注册完成账号后,会有一个秘钥,上传文件的时候进行授权和认证。
4、文件上传测试
二、封装工具类完成用户头像的上传和回显
1、导入依赖pom.xml
2、编写qiniu.properties
3、编写QiNiuConfig.java
4、编写QiNiuUtil.java
5、测试工具类
6、点击图片并会显示,本地图片回显
7、提交表单后进行上传图片和保存用户
创建完成后,后期上传的静态资源,可以根据域名+文件名直接访问,自定义域名必须是备案域名
进入七牛云开发者中心
导包:
com.qiniu
qiniu-java-sdk
7.2.11
com.google.code.gson
gson
2.8.6
测试:
package com.rk.app.utils;
import com.google.gson.Gson;
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.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
public class TestQiniu {
public static void main(String[] args) {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Zone.zone2());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
String accessKey = "i5cpjX4RbOAzPNaYeR_DvCAZx3HJcmkm2il0JBSN";
String secretKey = "你自己的";
String bucket = "rk123";//空间名
//如果是Windows情况下,格式是 D:\\qiniu\\test.png
String localFilePath = "D:\\桌面\\图片素材\\rkpic.jpg";
//默认不指定key的情况下,以文件内容的hash值作为文件名
//存储空间的文件名
String key = null;
//身份认证
Auth auth = Auth.create(accessKey, secretKey);
//指定覆盖上传
String upToken = auth.uploadToken(bucket,key);
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);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
}
}
不指定上传的文件名,文件名默认就是hash,现在去七牛云上的rk123空间中查看
可以通过该空间的默认域名+文件名直接访问该静态资源
http://rbrbsa8ab.hn-bkt.clouddn.com/FogxvGEKrWWgDcj9Jt3F-aBIkOvL
com.qiniu
qiniu-java-sdk
7.2.11
com.google.code.gson
gson
2.8.6
# 七牛云配置
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
package com.rk.app.config;
import com.qiniu.common.Zone;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.Properties;
/**
* 七牛云配置
*
**/
@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());
}
}
package com.rk.app.utils;
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 com.rk.app.config.QiNiuConfig;
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;
/**
* 七牛上传下载工具类
*
**/
@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;
}
}
public class TestQiniu {
public static void main(String[] args) throws UnsupportedEncodingException {
Boolean flag=QiNiuUtil.upload("D:\\桌面\\图片素材\\cloud.jpg","wang",true);
if(flag){
System.out.println("获取文件访问路径:"+QiNiuUtil.fileUrl("wang"));
}else {
System.out.println("上传失败!!");
}
}
}
头像
当修改上传的图片时触发事件,获取本地图片的
$('#pimage').change(function(e) {
var img = e.target.files[0];
var imgSrc = URL.createObjectURL(img);
$("#imgDiv").empty(); //清空原有数据
//创建img 标签对象
var imgObj = $("
");
//给img标签对象追加属性
imgObj.attr("src",imgSrc);//设置图片路径
imgObj.attr("width","100px");//设置宽
imgObj.attr("height","100px");//设置高
//将图片img标签追加到imgDiv末尾
$("#imgDiv").append(imgObj);
});
要提交的表单加上 enctype="multipart/form-data" 属性
后端接口:
@RequestMapping("/saveUsers")
public Boolean saveUsers(@RequestParam(value = "avatar",required = false)
MultipartFile avatar, HttpServletRequest request) {
Users user = new Users();
String imageName= StrUtils.getComplexRandomString(5);
//文件上传
Boolean flag=QiNiuUtil.uploadMultipartFile(avatar,imageName,true);
if(!flag){//上传失败
return false;
}
//设置头像链接
user.setAvatar(FileUrl.image+imageName);
System.out.println("图片访问连接:"+FileUrl.image+imageName);
//用来获取其他参数
MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
//设置其他属性
user.setUname(params.getParameter("uname"));
user.setNickname(params.getParameter("nickname"));
System.out.println("昵称"+params.getParameter("nickname"));
user.setSex(params.getParameter("sex"));
user.setRemark(params.getParameter("remark"));
//设置加密密码
user.setPassword(new Md5Hash(params.getParameter("password"),
user.getUname() + params.getParameter("password"),
1000).toString()
);
return usersService.save(user);
}
MultipartFile avatar用来接收表单传递过来的文件,将request转换为 MultipartHttpServletRequest对象,来获取表单其它内容
MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);