后台获取七牛token代码:
maven 配置
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.11</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.3.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>happy-dns-java</artifactId>
<version>0.1.4</version>
<scope>compile</scope>
</dependency>
获取token接口
/**
* 七牛获取token
*/
@RequestMapping(value = "/getQinuToken", method = RequestMethod.POST)
@ResponseBody
public ApiResult<String> getQinuToken(@RequestBody Map<String , Object> param){
if(null == param.get("key") || StringUtils.isBlank((String)param.get("key"))) {
return ApiResult.error(getMessage("qinuKeyNotBlank.error"));
}
return ApiResult.success(SimpleUpload.getUpToken((String)param.get("key")));
};
获取token 工具类
package com.qkkj.operatemgmt.framework.util;
import java.io.File;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
/**
* 七牛 java sdk 简单上传,覆盖上传,文件上传
* @author wangfudong
*/
public class SimpleUpload {
//设置好账号的ACCESS_KEY
private static final String ACCESS_KEY = "..";
//设置好账号的SECRET_KEY
private static final String SECRET_KEY = "..";
//上传凭证有效时长24小时,单位:秒
private static long expireSeconds = 86400;
//要上传的空间
private static String BUCKET_NAME = "...";
/**
* 获取凭证
* @param qkkj-file 空间名称
* @param key 覆盖上传
* @return
*/
public static String getUpToken(String key) {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
return auth.uploadToken(BUCKET_NAME, key, expireSeconds, null);
}
/**
* 获取凭证
* @param bucketName 空间名称
* @param key 覆盖上传
* @return
*/
public static String getUpToken(String bucketName,String key) {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
return auth.uploadToken(bucketName, key, expireSeconds, null);
}
/**
* 上传方法1
* @param filePath 文件路径 (也可以是字节数组、或者File对象)
* @param key 上传到七牛上的文件的名称 (同一个空间下,名称【key】是唯一的)
* @param bucketName 空间名称 (这里是为了获取上传凭证)
*/
public static void upload(String filePath, String key, String bucketName) {
try {
// 调用put方法上传
Configuration config = new Configuration();
UploadManager uploadManager = new UploadManager(config);
Response res = uploadManager.put(filePath, key, getUpToken(bucketName,key));
// 打印返回的信息
System.out.println(res.bodyString());
} catch (QiniuException e) {
Response r = e.response;
// 请求失败时打印的异常的信息
System.out.println(r.toString());
try {
// 响应的文本信息
System.out.println(r.bodyString());
} catch (QiniuException qe) {
// ignore
}
}
}
/**
* 上传方法2
* @param file 文件
* @param key 上传到七牛上的文件的名称 (同一个空间下,名称【key】是唯一的)
* @param bucketName 空间名称 (这里是为了获取上传凭证)
*/
public static void upload(File file, String key, String bucketName) {
try {
// 调用put方法上传
Configuration config = new Configuration();
UploadManager uploadManager = new UploadManager(config);
Response res = uploadManager.put(file, key, getUpToken(bucketName,key));
// 打印返回的信息
System.out.println(res.bodyString());
} catch (QiniuException e) {
Response r = e.response;
// 请求失败时打印的异常的信息
System.out.println(r.toString());
try {
// 响应的文本信息
System.out.println(r.bodyString());
} catch (QiniuException qe) {
// ignore
}
}
}
/**
* 上传方法3 覆盖上传
* @param path
* 上传文件路径
* @param bucketName
* 空间名
* @param key
* 文件名
*/
public void overrideUpload(String path, String key, String bucketName) {
try {
String token = getUpToken(bucketName, key);//获取 token
Configuration config = new Configuration();
UploadManager uploadManager = new UploadManager(config);
Response response = uploadManager.put(path, key, token);//执行上传,通过token来识别 该上传是“覆盖上传”
System.out.println(response.toString());
} catch (QiniuException e) {
System.out.println(e.response.statusCode);
e.printStackTrace();
}
}
}
js代码
//点击多图片上传
function uploadPictures() {
//清空未上传文件的iframe表单
if($('input[name=token]').length){
var size = $('input[name=token]').length;
for(var i = 0 ; i<size ; i++){
if($($('input[name=token]')[i]).val()==""){
var divId = $($($('input[name=token]')[i]).parent().parent()).attr("ID");
$("#"+divId).remove();
}
}
}
//生成formId
var uuid = Math.uuidFast();
//form Html
var formContent = '<form name="formQinu" id="'+uuid+'" method="post" action="https://upload-z1.qiniup.com" enctype="multipart/form-data" target="ajax'+uuid+'">'
+'<input name="accept" value="text/plain"/>'
+'<input name="key" value="">'
+'<input name="token" value="">'
+'<input type="file" name="file" id="file'+uuid+'"/></form>';
//把iframe表单添加到div中
$("#uploadFilesId").append('<div id="div'+uuid+'"></div>');
$("#div"+uuid).append(formContent);
$("#div"+uuid).append('<iframe name="ajax'+uuid+'" style="display:none"></iframe>');
//绑定onchange事件
$("#file"+uuid).change(function() {
var file = $(this)[0];
if (file.files && file.files[0]) {
var reader = new FileReader();
reader.onload = function(evt) {
$('#preview').append('<a href="javascript:void(0);" οnclick="delCurrentPictrue(this)" id="aimg'+uuid+'"><img id="img'+uuid+'" src="' + evt.target.result + '" /></a>');
}
reader.readAsDataURL(file.files[0]);
} else {
$('#preview').append('<a href="javascript:void(0);" οnclick="delCurrentPictrue(this)" id="aimg'+uuid+'"><div id="img'+uuid+'" class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div></a>');
}
if(file){
var urlPath = file.value;
var pictreType = urlPath.substr(urlPath.lastIndexOf('.')+1,urlPath.length);
var uuidkey = Math.uuidFast();
var currentDate = getNowFormatDate();
//获取上传文件名 : mallShowImage/当前日期(格式:yyyy-MM-dd)/uuid的值+图片后缀
var uploadName = "mallShowImage/"+currentDate+"/"+uuidkey+pictreType
//获取七牛token
$.ajax({
url: requestMapping.BALQINIUGETTOKEN,
data:JSON.stringify({key:uploadName}),
type: "POST",
success: function(data) {
if(data.code == resultCode.SUCCESS) {
//设置上传文件名
$("#"+uuid+" input[name=key]").val(uploadName);
//设置七牛token
$("#"+uuid+" input[name=token]").val(data.data);
}
else if(data.code == resultCode.ERROR) {
alert("获取qiniuToken失败!");
}
}
});
}
});
//删除事件
$("#img"+uuid).click(function(){
alert("要开始删除了")
})
//弹出上传文件筐
$("#file"+uuid).click();
}
//保存
function formQinuSubmit(){
//清空未上传文件的iframe表单
if($('input[name=token]').length){
var size = $('input[name=token]').length;
for(var i = 0 ; i<size ; i++){
if($($('input[name=token]')[i]).val()==""){
var divId = $($($('input[name=token]')[i]).parent().parent()).attr("ID");
$("#"+divId).remove();
}
}
}
//循环已经上传文件的iframe表单上传七牛
if($('form[name=formQinu]').length){
for(var i = 0 ; i<$('form[name=formQinu]').length ; i++){
//获取key
var qiniukey = $($($('form[name=formQinu]')[i]).find('input[name=key]')).val();
var qiniuUrl = 'http://p8t6un99a.bkt.clouddn.com/'+qiniukey;
//提交当前循环的iframe表单
$($('form[name=formQinu]')[i]).submit();
}
}
//定时检测
var interval = setInterval(function(){
var countUpload = 0;
if($('form[name=formQinu]').length){
for(var i = 0 ; i<$('form[name=formQinu]').length ; i++){
//获取key
var qiniukey = $($($('form[name=formQinu]')[i]).find('input[name=key]')).val();
var qiniuUrl = 'http://p8t6un99a.bkt.clouddn.com/'+qiniukey;
//检测路径有效性
$.ajax({
url: qiniuUrl,
type: "GET",
urlQinu : true,
success: function() {
countUpload = countUpload+1;
if(countUpload!=$('form[name=formQinu]').length){
console.log("第"+countUpload+"张图片上传成功,图片名称");
}else{
console.log("第"+countUpload+"张图片--最后一张上传成功,开始调用后台。。。。");
clearInterval(interval);//终止循环
$.ajax({
url: requestMapping.BALCARDCOUPONSSELLADD_REQUEST,
formId: "qkkj-add-form",
type: "POST",
success: function(data) {
if(data.code == resultCode.SUCCESS) {
$('#myModal').modal({
keyboard: true
});
$('#close').hide();
$('#modal-body').html("添加成功!");
}
else if(data.code == resultCode.ERROR) {
$('#myModal').modal({
keyboard: true
});
$('#close').show();
$('#modal-body').html(data.msg);
}
}
});
}
},
error: function(){
alert("第"+i+"图片上传失败!!");
}
});
}
}
}, 3000);
}
//删除图片事件
function delCurrentPictrue(object){
//获取图片id
var aimgId = $(object).attr("ID");
//获取当前图片以及对应表单的通用uuid = formId
var picuuid = aimgId.substr(4,aimgId.length);
//删除iframe 表单div
var divIframe = "div"+picuuid;
$("#"+divIframe).remove();
//删除图片
$(object).remove();
}
//验证上传图片路径有效性,要解决跨域问题js
jquery.xdomainrequest.min.js 网上找的
页面html:
<div id="preview"></div>
<button type="button" class="btn btn-primary" οnclick="uploadPictures();">批量上传图片</button>
<div id="uploadFilesId">
</div>