之前在后端上传视频到七牛云上,发现上传速度很慢,后来尝试直接在前端上传视频到七牛云上,最后实测发现快了很多。采用前端上传也减轻了服务器压力。
七牛云存储示例:http://jssdk.demo.qiniu.io/
官方SDK:https://developer.qiniu.com/kodo/sdk/1283/javascript
swf文件下载SDK里面有
下载地址:https://github.com/qiniu/js-sdk/releases
1、后台生成token字符串给前端:
pom文件引入
com.qiniu
qiniu-java-sdk
[7.2.0, 7.2.99]
QiNiuUtil工具类
package com.jcmx.common.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;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
public class QiNiuUtil {
static Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
public static final String accessKey = "";//公钥
public static final String secretKey = "";//秘钥
public static final String bucket = "";//空间名
public static final String path = "";//加速域名
public static String uploadToken(FileInputStream file, String key) {
Configuration cfg = new Configuration(Zone.zone0());//华东地区
UploadManager uploadManager = new UploadManager(cfg);
logger.info("path=" + path);
try {
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
System.out.println("token:"+upToken);
//初始化时区对象,北京时间是UTC+8,所以入参为8
ZoneOffset zoneOffset=ZoneOffset.ofHours(8);
//初始化LocalDateTime对象
LocalDateTime localDateTime=LocalDateTime.now();
//获取LocalDateTime对象对应时区的Unix时间戳
System.out.println(localDateTime.toEpochSecond(zoneOffset));
Long e = localDateTime.toEpochSecond(zoneOffset);
try {
Response response = uploadManager.put(file, key, upToken, null, null);
//解析上传成功的结果
//DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
logger.info("key:" + putRet.key);
String encodedFileName = URLEncoder.encode(putRet.key, "utf-8");
//获取下载地址
/*String finalUrl1 = path+"/"+putRet.key;*/
String finalUrl = String.format("%s/%s", path, encodedFileName);//七牛云公有空间
String finalUrl1 = auth.privateDownloadUrl(finalUrl,e);//七牛云私有空间路径访问需给路径授权
logger.info("访问地址:" + finalUrl1);
return finalUrl1;
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**生成Token*/
public static String getToken() {
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
return upToken;
}
}
生成token
//七牛Token
@GetMapping("/gettoken")
@ResponseBody
public Map uptoken(){
Map resultMap = new HashMap<>();
String token = QiNiuUtil.getToken();
resultMap.put("uptoken",token);
return resultMap;
}
2、编写前端代码:
导入JS文件(这里我就不贴代码了,通过七牛云存储示例F12就可以看到对应的JS和css,拷贝到自己的项目里就可以了)
这里我把自己整理的js传到了GitHub上了,下载地址:https://github.com/CAPTAIN-JIE/qiniuUpload.git
这是我整理后放到项目里的js目录
页面引入JS文件
引入css样式
Html页面上传视频按钮
选择文件
请上传800M以内的MP4文件
JavaScript编写
/*撤销视频*/
$('#videoRevoke').bind('click',function(){
$("#container").css("display","block");
$('#success').css("display","none");
$('#videoRevoke').css("display","none");
$('#video_url').remove();
$('#fsUploadProgress>tr').remove();
})
通过隐藏标签获取上传视频路径传到后端保存到数据库
var resourcesUrl = document.getElementById("video_url").src;
到此上传视频的功能就完成了。
下面贴上上传图片的方法(因为图片比较小,对速度影响不大,这里我是通过后端上传的图片)
1、前端代码编写:
Html页面上传图片按钮
请上传尺寸为750*440的图片!
JavaScript编写
/*撤销图片*/
$('#imageRevoke').bind('click',function(){
var imgobj = document.getElementById('imgs');
imgobj.removeAttribute('src');
$("#imageupload").attr("disabled",false);
$('#msg').css("display","none");
var imageUrl = document.getElementById('image_url');
imageUrl.removeAttribute('src');
})
2、后台代码:
@ApiOperation(value = "上传图片")
@PostMapping("/uploadImage")
@ResponseBody
public Editor uploadImage(@RequestParam("uploadImage") MultipartFile multiple, HttpSession session, HttpServletRequest request) throws IOException {
if (multiple != null) {
String [] str = upload(multiple);
return Editor.ResultUtil.success(str);
}
return Editor.ResultUtil.success();
}
public String [] upload(MultipartFile multiple){
FileInputStream inputStream = null;
try {
inputStream = (FileInputStream) multiple.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = multiple.getOriginalFilename();
String fileNameExtension = fileName.substring(fileName.lastIndexOf("."), fileName.length());
String realName = String.valueOf(System.currentTimeMillis()) + ShiroUtils.getLoginName() + fileNameExtension;
String path = QiNiuUtil.uploadToken(inputStream, realName);
String [] str = {path};
return str;
}
以上是js上传文件到七牛云上的步骤,欢迎大家提供好的建议!