PLUpload上传文件到七牛云

上传文件到七牛云存储,各种demo,网上一搜一堆,官网上的示例对刚接触的人不是很友好,写的很笼统,下面我就将我自己摸索经验的分享给大家。


1.首先你需要注册一个七牛的账号,七牛会给你提供AccessKey 和 SecretKey    后续生成upToken会使用到,只要涉及到与七牛服务打交道的这公钥和私钥这两个参数是少不了的!

然后你需要下载七牛提供的JS-SDK ,也有在线示例,我在最初使用的时候看人家的示例没问题,自己集成上去全是问题!(无奈啊!)


JS-SDK下载

JS-SDK在线示例


2.七牛文件上传涉及服务端需要颁发token,生成token的SDK七牛也会提供给你。SDK下载,链接我在这里发出来,目前主流语言都是支持的,我是用的JAVA,所以打开网页进去直接下载就行,如图:



 3.下载后需要集成到项目中,SDK文档中有详细的教程,这里我就不一一说明了!下面我把我的生成token的策略代码贴出来:


@RequestMapping("/token.htm")
public void token(HttpServletResponse resp){
Properties p = PropertiesUT.getProperties(WebUT.realPath("/WEB-INF/config")+File.separator+"web.properties");

String time =DateUT.getFormatTime().replaceAll(" ", "/");

String key= time+"/"+String.valueOf(DataPfopCommon.buildRandom(10));//给上传的文件生成文件名称

String bucket=Constants.BUCKET_EAST_BUCKET;//这是七牛云对象存储的空间名称

//数据处理指令,支持多个指令
//String saveMp4Entry = String.format("%s:"+key+".mp4", bucket);//
String saveWmVideoEntry = String.format("%s:"+key+".wm", bucket);

String wmImage=UrlSafeBase64.encodeToString("http://eascdn.52k12.com/logo1.png");//给视频添加水印的图片地址,该图片需要预先在存储空间中上传好!这里只需要外链

String wmGravityText="SouthEast";//水印添加的位置

//转码并打图片水印
//String avthumbMp4Fop = String.format("avthumb/mp4/%s", UrlSafeBase64.encodeToString(saveMp4Entry));
//String vframePngFop = String.format("vframe/png/offset/1/|saveas/%s", UrlSafeBase64.encodeToString(savePngEntry));
String wmVideoFop = String.format("avthumb/mp4/wmImage/"+wmImage+"/wmGravityText/"+wmGravityText+"|saveas/%s", UrlSafeBase64.encodeToString(saveWmVideoEntry));

//将多个数据处理指令拼接起来
String persistentOpfs = StringUtils.join(new String[]{wmVideoFop}, ";");
StringMap stringMap=new StringMap();
stringMap.put("persistentOps", persistentOpfs);
stringMap.put("persistentNotifyUrl","http://172.30.250.1/qiniuNotice/PersistentCallBack.htm" );//p.getProperty("qiniu_notify_url")//这是持久化任务处理成功后七牛回调业务服务器的地址
stringMap.put("persistentPipeline", "video-handle");//这个是你持久化处理的队列名称
stringMap.put("saveKey", key);//文件的key //调用api生成token String token=DataPfopCommon.qiniuResPfop(null, Constants.BUCKET_EAST_BUCKET, stringMap, null, null, true);
JSONObject obj=new JSONObject();
obj.put("uptoken", token);
outPrintJson(obj.toString(), resp);
}


4.然后在JS-SDK中使用Ajax请求该接口,获取token。下面我会贴出调用JS-SDK的代码:


//视频上传组件
$(function(){
var uploader = Qiniu.uploader({
runtimes: 'html5,flash,html4', // 上传模式,依次退化
browse_button: 'pickfiles', // 上传选择的点选按钮,必需
uptoken_url:$('#videoToken').val(),
filters : {
//prevent_duplicates: true,//不允许选取重复文件
mime_types: [
{title : "Video files", extensions : "flv,mpg,mpeg,avi,wmv,mov,asf,rm,rmvb,mkv,m4v,mp4"}
]
},
get_new_uptoken: false, // 设置上传文件的时候是否每次都重新获取新的uptoken
domain: $('#domain').val(), // bucket域名,下载资源时用到,必需
container: 'container', // 上传区域DOM ID,默认是browser_button的父元素
flash_swf_url: '$!{__public}/plugins/qnupload/plupload/Moxie.swf', //引入flash,相对路径
max_retries: 3, // 上传失败最大重试次数
max_file_size : '2048MB',
chunk_size: '4mb', // 分块上传时,每块的体积
auto_start: true, // 选择文件后自动上传,若关闭需要自己绑定事件触发上传
save_key:true,
init: {
'FilesAdded': function(up, files) {
// 文件添加进队列后,处理相关的事情
$("#Progress").attr("width","0%");
$("#Progress").text("0%");
$("#uploadSpeed").text("已上传:0MB 上传速度:0KB/s");
},
'BeforeUpload': function(up, file) {
// 每个文件上传前,处理相关的事情
$("#dataProgress").show();
},
'UploadProgress': function(up, file) {
// 每个文件上传时,处理相关的事情
var size = plupload.formatSize(file.loaded).toUpperCase();
var formatSpeed = plupload.formatSize(file.speed).toUpperCase();
var dataDoms="<div class=\"progress-bar progress-bar-info\" id=\"Progress\" style=\"width:"+file.percent+"%;\" role=\"progressbar\" aria-valuenow=\"0\" aria-valuemax=\"100\" aria-valuemin=\"0\">"+file.percent+"%</div>"
$("#uploadSpeed").text("已上传:"+size+" 上传速度:"+formatSpeed+"/s");
$("#dataProgress").html(dataDoms);
},
'FileUploaded': function(up, file, info) {
$("#uploadSpeed").remove();
$("#dataProgress").remove();
console.log(info);
layer.msg('视频上传成功', {icon : 1,time : 1000,shade : 0.5});
// 每个文件上传成功后,处理相关的事情
// 查看简单反馈
var fileSize = plupload.formatSize(file.size).toUpperCase();//文件大小
var domain = up.getOption('domain');
var res = eval("("+info+")");
var sourceLink = domain + res.key;// 获取上传成功后的文件的Url
var resDoms=genTableDoms(res.key,file.name, sourceLink, fileSize);
$("#videoUrl").val(sourceLink);
$("#videoinfo").show();
$("#dataTable tbody").append(resDoms);
},
'Error': function(up, err, errTip) {
//上传出错时,处理相关的事情
layer.msg('视频上传出错:'+errTip, {icon : 2,time : 2000,shade : 0.5});
},
'UploadComplete': function() {
//队列文件处理完毕后,处理相关的事情
},
'Key': function(up, file) {
/* var nowTime=getNowFormatDate();
var key = nowTime+ " " +file.name;;
return key */
}
}
});

//------------------------------------图片-------------------------------
var Q2 = new QiniuJsSDK();
var uploader2 = Q2.uploader({
runtimes: 'html5,flash,html4', // 上传模式,依次退化
browse_button: 'pickfilesIMG', // 上传选择的点选按钮,必需
uptoken_url:$('#imageToken').val(),
filters : {
// prevent_duplicates: true,//不允许选取重复文件
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"}
]
},
get_new_uptoken: false, // 设置上传文件的时候是否每次都重新获取新的uptoken
domain: $('#domain').val(), // bucket域名,下载资源时用到,必需
max_file_size : '1000mb', // 最大文件体积限制
container: 'container2', // 上传区域DOM ID,默认是browser_button的父元素
flash_swf_url: '$!{__public}/plugins/qnupload/plupload/Moxie.swf', //引入flash,相对路径
max_retries: 3, // 上传失败最大重试次数
chunk_size: '10mb', // 分块上传时,每块的体积
auto_start: true, // 选择文件后自动上传,若关闭需要自己绑定事件触发上传
save_key:true,
init: {
'FilesAdded': function(up, files) {
/* $("#uploadSpeed").remove();
$("#tbody").remove();*/
// 文件添加进队列后,处理相关的事情
$("#Progress").attr("width","0%");
$("#Progress").text("0%");
$("#uploadSpeed").text("已上传:0MB 上传速度:0KB/s");
},
'BeforeUpload': function(up, file) {
// 每个文件上传前,处理相关的事情
$("#dataProgress").show();
},
'UploadProgress': function(up, file) {
// 每个文件上传时,处理相关的事情
var size = plupload.formatSize(file.loaded).toUpperCase();
var formatSpeed = plupload.formatSize(file.speed).toUpperCase();
var dataDoms="<div class=\"progress-bar progress-bar-info\" id=\"Progress\" style=\"width:"+file.percent+"%;\" role=\"progressbar\" aria-valuenow=\"0\" aria-valuemax=\"100\" aria-valuemin=\"0\">"+file.percent+"%</div>"
$("#uploadSpeed").text("已上传:"+size+" 上传速度:"+formatSpeed+"/s");
$("#dataProgress").html(dataDoms);
},
'FileUploaded': function(up, file, info) {
$("#uploadSpeed").remove();
$("#dataProgress").remove();
console.log(info);
layer.msg('图片上传成功', {icon : 1,time : 1000,shade : 0.5});
// 每个文件上传成功后,处理相关的事情
// 查看简单反馈
var fileSize = plupload.formatSize(file.size).toUpperCase();//文件大小
var domain = up.getOption('domain');
var res = eval("("+info+")");
$("#qnVideoKey").val(res.key);
var sourceLink = domain + res.key;// 获取上传成功后的文件的Url
var resDoms=genTableDoms(res.key,file.name, sourceLink, fileSize,file.type);
$("#imgUrl").val(sourceLink);
$("#videoinfo").show();
$("#dataTable tbody").append(resDoms);
},
'Error': function(up, err, errTip) {
//上传出错时,处理相关的事情
layer.msg('图片上传出错:'+errTip, {icon : 2,time : 2000,shade : 0.5});
},
'UploadComplete': function() {
//队列文件处理完毕后,处理相关的事情
},
'Key': function(up, file) {
/* var nowTime=getNowFormatDate();
var key = nowTime+ " " +file.name;;
return key */
}
}
});
})

//上传后生成文件列表
function genTableDoms(key,fileName,resUrl,fileSize,fileType){
var taableDoms="<tr class=\"text-c\"> "+
"<td>"+fileName+"</td> "+
"<td>"+resUrl+"</td> "+
"<td>"+fileSize+"</td> "+
"<td>"+
"<a title=\"删除\" href=\"javascript:;\" onclick=\"delVideo(this,'"+key+"')\" class=\"ml-5\" style=\"text-decoration:none\"><i class=\"Hui-iconfont\"></i></a> "+
"<a title=\"预览\" href=\"javascript:;\" onclick=\"showVideo('"+resUrl+"','"+fileType+"')\" class=\"ml-5\" style=\"text-decoration:none\"><i class=\"Hui-iconfont\"></i></a> "+
"</td>"+
"</tr> ";
return taableDoms;
}


因为这个功能是2016年在公司写的,所以现在拿出来和大家分享,写的不是很完整,但代码都有,注释也有通俗易懂。如果大家需要的话可以联系我,我会整理出来分享给大家。

需要注意生成token的代码,如果你只想把文件上传上去,那么你只需要指定文件的key就行,也可以不用指定,plupload会自动生成文件名。现在七牛的开发者文档完善的不错了(我接触那会文档真的让人抓狂

猜你喜欢

转载自blog.csdn.net/q1664197389/article/details/80617895