)
一、使用前准备
accessKey:七牛云个人中心查看
secretKey:七牛云个人中心查看
bucket:七牛云对象存储-空间管理-空间名称
zone:# [{‘zone0’:‘华东’},{‘zone1’:‘华北’},{‘zone2’:‘华南’},{‘zoneNa0’:‘北美’},{‘zoneAs0’:’’}] 例如:“zone1”
#这里是存储空间的区域,建议选择华东,在七牛云自己配置,这里我们公司使用的华北
domainOfBucket:存储空间访问的路径
项目是springboot项目。
二、pom.xml引入
下面展示一些 内联代码片
。
<!--七牛 -->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
三、创建配置文件 QiNiuConfig.java
QiNiuConfig.java代码
package com.aproject.common.utils;
import java.util.Properties;
import com.qiniu.common.Zone;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Data
public class QiNiuConfig {
private String accessKey;
private String secretKey;
private String bucket;
private Zone zone;
private String domainOfBucket;
private long expireInSeconds;
private String domain;
private static QiNiuConfig instance = new QiNiuConfig();
private QiNiuConfig(){
try {
//prop.load(QiNiuConfig.class.getResourceAsStream("/application.properties"));
accessKey = "你的accessKey ";
secretKey = "你的secretKey";
bucket = "你的储存空间名称";
domainOfBucket = "绑定该储存空间的域名地址/你的储存空间名称";
domain="绑定该储存空间的域名地址/";
expireInSeconds = Long.parseLong("3600");
String zoneName = "zone1";
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 Zone getZone(){
return zone;
}
public String getAccessKey(){
return accessKey;
}
public String getSecretKey() {
return secretKey;
}
public String getBucket() {
return bucket;
}
public String getDomainOfBucket() {
return domainOfBucket;
}
public long getExpireInSeconds() {
return expireInSeconds;
}
public String getDomain() {
return domain;
}
public static void main(String[] args) {
System.out.println(QiNiuConfig.getInstance().accessKey);
}
}
四、使用示例 QiNiuUtils.java
package com.aproject.common.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.web.multipart.MultipartFile;
import com.aproject.common.exception.file.FileNameLengthLimitExceededException;
import com.aproject.common.exception.file.FileSizeLimitExceededException;
import com.aproject.common.exception.file.InvalidExtensionException;
import com.aproject.common.utils.file.FileUploadUtils;
import com.aproject.common.utils.file.MimeTypeUtils;
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;
@SuppressWarnings("all")
@Slf4j
public class QiNiuUtils {
/**
* 上传本地文件
* @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 = "https://upload-z2.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 InvalidExtensionException
* @throws FileSizeLimitExceededException
* @throws IOException
*/
public static String uploadMultipartFile(MultipartFile file, boolean override) throws FileSizeLimitExceededException, InvalidExtensionException {
//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(QiNiuConfig.getInstance().getZone());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//把文件转化为字节数组
InputStream is = null;
ByteArrayOutputStream bos = null;
int fileNamelength = file.getOriginalFilename().length();
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
{
throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
}
FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
String fileName = file.getOriginalFilename();
String extension = FileUploadUtils.getExtension(file);
fileName = FileUploadUtils.encodingFilename(fileName) + "." + extension;
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(), fileName);//覆盖上传凭证
}else{
upToken = auth.uploadToken(QiNiuConfig.getInstance().getBucket());
}
//默认上传接口回复对象
DefaultPutRet putRet;
//进行上传操作,传入文件的字节数组,文件名,上传空间,得到回复对象
Response response = uploadManager.put(uploadBytes, fileName, upToken);
putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);//key 文件名
System.out.println(putRet.hash);//hash 七牛返回的文件存储的地址,可以使用这个地址加七牛给你提供的前缀访问到这个视频。
return QiNiuConfig.getInstance().getDomain()+putRet.hash;
}catch (QiniuException e){
e.printStackTrace();
return null;
}catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static Auth getAuth(){
Auth auth = Auth.create(QiNiuConfig.getInstance().getAccessKey(), QiNiuConfig.getInstance().getSecretKey());
return auth;
}
public static void main(String[] args) {
System.out.println(upload("E:\\SSC\\宗亲商城\\front\\h5\\unpackage\\dist\\build\\h5\\static\\tab\\tab-home-current.png", "123.png", true));
}
}
五、uniapp前端使用
//调用摄像头拍摄
let _this = this;
uni.chooseVideo({
count: 1,
sourceType: ['camera', 'album'],
success: function(res) {
console.log(res)
_this.src = res.tempFilePath;
}
});
//调用照相机拍照片
uni.chooseImage({
count: 1, //上传图片的数量,默认是9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
_this.videoCover=tempFilePaths[0];
console.log('chooseImageRes',chooseImageRes)
}
});
//上传后端
//上传视频
uni.uploadFile({
url: this.$host+"api/video/uploadFileQiNiu",
method: "POST",
header: {
'token': uni.getStorageSync('token'),
},
filePath: _this.videoSrc,
name: 'file',
success: (res) => {
//let videoUrls = JSON.parse(res.data) //微信和头条支持
let videoUrls = res.data //百度支持
console.log(videoUrls);
console.log(JSON.parse(res.data));
_this.videoSrc=JSON.parse(res.data).data.fileName
uni.uploadFile({
method: "POST",
url: this.$host+"api/video/uploadFileQiNiu", //仅为示例,非真实的接口地址
filePath: _this.videoCover,
name: 'file',
header: {
'token': uni.getStorageSync('token'),
},
success: (uploadFileRes) => {
console.log(uploadFileRes);
console.log(JSON.parse(uploadFileRes.data));
_this.videoCover=JSON.parse(uploadFileRes.data).data.fileName;
//提交数据
_this.subAll();
},
fail: function(res) {
uni.showToast({
title: "网络异常",
icon: 'none',
duration: 1000
});
uni.hideLoading();
}
});
},
fail: function(res) {
uni.showToast({
title: "网络异常",
icon: 'none',
duration: 1000
});
uni.hideLoading();
}
})
六、uniapp查看视频
<template>
<view class="pageAll">
<video :style="{height: windowHeight}" class="myVideo" id="myVideo" :loop="true" :src="videoSrc" @error="videoErrorCallback" autoplay=true :enable-progress-gesture="true" :show-fullscreen-btn="false" :show-center-play-btn="false" @play="videoPlay" @click="videoPause" >
</video>
</view>
</template>
<script>
data() {
return {
id:-1,
name:'',
introduction:'',
details: '',
createTime:'',
videoVote:0,
videoShareNum:0,
videoPic:'',
windowHeight: 0,
isPlay: true,
videoSrc: '',
}
},
onLoad: function(o) {
console.log('ooo',o)
this.videoContext = uni.createVideoContext('myVideo')
this.topHeight=uni.getSystemInfoSync().statusBarHeight+20;
//this.videoContext.requestFullScreen();
let _this = this;
uni.getSystemInfo({
success: function(res) {
_this.windowHeight = res.windowHeight + 'px';
}
});
},
onShow: function() {
this.videoContext = uni.createVideoContext('myVideo')
//this.videoContext.requestFullScreen();
},
onReady: function(res) {
this.videoContext = uni.createVideoContext('myVideo')
//this.videoContext.requestFullScreen();
},
methods: {
videoPause: function(e) {
console.log(e)
let _this = this;
_this.isPlay = true;
this.videoContext.pause();
},
videoPlay: function(e) {
console.log(e)
let _this = this;
this.videoContext.play();
_this.isPlay = false;
},
videoErrorCallback: function(e) {
// console.log(e)
// uni.showModal({
// content: e.target.errMsg,
// showCancel: true
// })
},
}
</script>