上传整个流程(图片上传需要截图)
裁剪:
上传插件:
弹窗:
文件下载地址:下载地址 提取码:agiw
图片裁剪
<div id="shear" style="display:none;width:800px;height: 400px;z-index: 99999999;">
<img src="" id="shear_img" style="width:800px;height:400px;"/>
div>
上传按钮布局
<div class="hwuploads">
<div class="hwupload hwupload-img">
<img src="/static/shared/images/hwupload-img.png" width="84px"/>
<input type="file" name="file" class="hwUploadbtn" data-role="hwUploadimg" accept="image/jpeg,image/png" />
div>
<div class="hwupload hwupload-audio">
<img src="/static/shared/images/hwupload-audio.png"/>
<input type="file" name="file" class="hwUploadbtn" id="upload" data-role="hwUploadaudio" accept="audio/mp3"/>
div>
div>
上传图片后
<div class="v1-homework-infobox" data-role="submitinfobox" data-img="prveimgbox">
<div class="v1-homework-info" data-role="submitImgbox">
{{# if(d.status == '06'){ }}
{{# layui.each(d.homeworkData.images, function(idx, items){ }}
<div class="v1-homework-infos hw-waidelbox" data-del="waiImg" data-img="prveimg">
<img src="{{items.url}}" data-uri="{{items.url}}"/>
<i class="layui-icon delfilebtn delfilebtnWai" data-resultid="{{items.resultid}}">ဆ</i>
</div>
{{# }); }}
{{# } }}
</div>
</div>
上传音频后
<div class="v1-homework-audiobox" style="padding: 0 0 10px;display: none;" data-role="submitAudiobox">
{{# if(d.status == '06'){ }}
{{# layui.each(d.homeworkData.audios, function(idx, items){ }}
<div class="v1-homework-audio hw-waidelbox" data-del="waiAudio" data-role="audioPreview" data-uri="{{items.url}}">
<i class="layui-icon delfilebtn delfilebtnWai">ဇ</i>
<div class="hwaudio-animate"></div>
<div><i>{{items.length}}</i>"</div>
</div>
{{# }); }}
{{# } }}
</div>
var answerQuestionData = {};//解答题文件
var answerQuestionDataWaiImg = []//外面的图片上传
var answerQuestionDataWaiAudio = []//外面的图片语音上传
$(document).on('change','[data-role="hwUploadaudio"]',function(input){
let uploadfile = input.currentTarget.files[0];
$(this).val('');
if(!uploadfile){
return;
}
var filetype = uploadfile.type.split(".")[0];
if (!window.FileReader) {
errorMsg('该浏览器不支持文件上传');
}
var imgfile = {};
let audios;//上传的文件结构名字
let _this = this;
if (window.FileReader) {
var reader = new FileReader();
reader.readAsDataURL(uploadfile);
reader.onload = async function() {
let html = '';
获取上传时音频的时长
let duration = await getAudioDuraion(this.result);
html = '+this.result+'">'+
'ဇ'+
''+
''+Math.floor(duration)+'"'+
'';
接口参数要的结构
audios = {
length:duration,
url:uploadfile,
fileid:''
};
将audios 参数放在answerQuestionDataWaiAudio中 全局
answerQuestionDataWaiAudio.push(audios);//非打回数据
$('[data-role="submitAudiobox"]').show();
$('[data-role="submitAudiobox"]').append(html);
}
}
});
function getAudioDuraion(url) {
return new Promise(function (resolve) {
let audioElement = new Audio(url);//audio获取音频时长
audioElement.addEventListener("loadedmetadata", function (_event) {
resolve(parseInt(audioElement.duration));
});
});
}
$(document).on('change','[data-role="hwUploadimg"]',function(input){
let uploadfile = input.currentTarget.files[0];
$(this).val('');
if(!uploadfile){
return;
}
var filetype = uploadfile.type.split(".")[0];
if (!window.FileReader) {
errorMsg('该浏览器不支持文件上传');
}
var imgfile = {};
let images;
let _this = this;
if (window.FileReader) {
var reader = new FileReader();
reader.readAsDataURL(uploadfile);
reader.onloadend = function (e) {
$('#shear > img').attr("src",e.target.result);
$('#shear > img').cropper({
aspectRatio: 'NAN',
viewMode:2,
crop: function(data) {}
}).cropper('replace', e.target.result);
var cropperLayer = layer.open({
type: 1,
title:'裁剪',
btn:['裁剪'],
shade:0,
area: ['800px', '500px'], //宽高
yes: function(index, layero){
var canVas = $('#shear > img').cropper('getCroppedCanvas',{width:800,height:400});
var ImageURL = canVas.toDataURL('image/jpeg');
imgfile = dataURLtoFile(ImageURL,uploadfile.name);//将base64图片转化为file文件方法
reader.readAsDataURL(imgfile);
reader.onload = async function() {
let html = '';
html = ''+
'+this.result+'" data-uri="'+this.result+'"/>'+
'ဆ'+
'';
获取上传图片的数据
let imageSize = await getImgeData(this.result);
images = {
width:imageSize.width,
height:imageSize.height,
file:imgfile,
fileid:''
};
answerQuestionDataWaiImg.push(images);
$('[data-role="submitinfobox"]').show();
$('[data-role="submitImgbox"]').append(html);
$(_this).parents('.v1-homework-submitarea').find('[data-role="submitImgbox"]').children().last().click(previewImages);
};
layer.close(cropperLayer);
},
content: $('#shear')
});
}
}
});
function getImgeData(result) {
return new Promise(function (resolve) {
var image = new Image();
image.src = result;
image.onload = function () {
resolve({width:this.width,height:this.height});
};
})
}
上传视频
$(document).on('change','.uploadbtn',function(input){
let uploadfile = input.currentTarget.files[0];
$(this).val('');
if(!uploadfile){
return;
}
var itemid = $(this).data('itemid');
var filetype = uploadfile.type.split(".")[0];
if (!window.FileReader) {
errorMsg('该浏览器不支持文件上传');
}
if(!answerQuestionData[itemid]){
answerQuestionData[itemid] = [];
}
var imgfile = {};
let answerData;
let _this = this;
if (window.FileReader) {
var reader = new FileReader();
reader.readAsDataURL(uploadfile);
上传视频
reader.onload = async function() {
let html = '';
switch (filetype) {
case 'video/mp4':
html = ''+
'this.result+'" width="98px" height="98px">'+
'+itemid+'">ဆ'+
' '+
'';
answerData = {
type:'02',
file:uploadfile,
};
break;
default : errorMsg('文件类型不支持');return;
}
answerQuestionData[itemid].push(answerData);
$(_this).parents('.swiper-slide').find('[data-role="uploadboxAnswers"]').append(html);
}
}
});
提交-音频
let submithomeworkall;
$(document).on('click','.v1-homework-submitbtn',async function(){
var indexs = layer.load(2,{shade: [0.5,'#fff']});
submithomeworkall = {
clsid:stutaskData.clsid,
taskid: stutaskData.taskid,
data:{}
};
submithomeworkall.data['homeworkData'] = {};//homeworkData数据
if(answerQuestionDataWaiAudio){
var indexs = layer.load(2,{shade: [0.5,'#fff']});
try{
for(let data of answerQuestionDataWaiAudio){
if(data.url){
上传uploadFile 到 oss
let fileData = await uploadFile(data.url,'07');
delete data.file;
data.fileid = fileData.fileid;
data.url = fileData.path;
}
submithomeworkall.data['homeworkData']['audios'] = data;
}
}catch (result) {
layer.close(indexs);
errorMsg('上传失败');
}
}
//音频上传
submithomeworkall.data['homeworkData']['audios'] = answerQuestionDataWaiAudio ;//外面的语音push
console.log('提交作业');
console.log(submithomeworkall);
console.log('提交作业');
api.request('/service/homework/submithomework',submithomeworkall,1).then(function (result) {
successMsg('上传成功',function(){
layer.close(indexs);
});
}).catch(function (result){
layer.close(indexs);
errorMsg('上传失败');
})
})
提交-图片
let submithomeworkall;
$(document).on('click','.v1-homework-submitbtn',async function(){
var indexs = layer.load(2,{shade: [0.5,'#fff']});
submithomeworkall = {
clsid:stutaskData.clsid,
taskid: stutaskData.taskid,
data:{}
};
submithomeworkall.data['homeworkData'] = {};//homeworkData数据
if(answerQuestionDataWaiImg){
var indexs = layer.load(2,{shade: [0.5,'#fff']});
try{
for(let data of answerQuestionDataWaiImg){
if(data.file){
上传uploadFile 到 oss
let fileData = await uploadFile(data.file,'01');
delete data.file;
data.fileid = fileData.fileid;
data.url = fileData.path;
}
submithomeworkall.data['homeworkData']['images'] = data;
}
}catch (result) {
layer.close(indexs);
errorMsg('上传失败');
}
}
//图片上传
submithomeworkall.data['homeworkData']['images'] = answerQuestionDataWaiImg ;//外面的图片push
console.log('提交作业');
console.log(submithomeworkall);
console.log('提交作业');
api.request('/service/homework/submithomework',submithomeworkall,1).then(function (result) {
successMsg('上传成功',function(){
layer.close(indexs);
});
}).catch(function (result){
layer.close(indexs);
errorMsg('上传失败');
})
})
var uploadFile = function(file,type){
return new Promise(async function (resolve,reject) {
let osssignature;
switch (type){
case '01':
获取对应的签名
osssignature = await get_signature('temp', {dirid: '201'});
break;
case '02':
osssignature = await get_signature('video');
break;
case '07':
osssignature = await get_signature('homeworkaudio');
break;
}
let host = osssignature['data']['host'];
let dir = osssignature['data']['dir'];
let ossData=new FormData();
ossData.append("key",dir + '/' + WebUploader.Base.guid('v')+'.'+file.name.substr(file.name.lastIndexOf(".") + 1));
ossData.append("policy",osssignature['data']['policy']);
ossData.append("OSSAccessKeyId",osssignature['data']['accessid']);
ossData.append("success_action_status",'200');
ossData.append("signature",osssignature['data']['signature']);
ossData.append("callback",osssignature['data']['callback']);
ossData.append('file',file);
try{
上传到oss
let savefiledata = await uploadOss(ossData,host);
保存文件获得fileid
let fileData = await savefile(savefiledata,type);
resolve(fileData);
}catch (e) {
reject(e);
}
});
};
function get_signature(type,data){
return new ApiRequest().request('/service/upload/' + type + 'signature',data);
}
function uploadOss(ossData,host) {
return new Promise(function (resolve,reject) {
$.ajax({
url: host,
data: ossData,
processData: false,
cache: false,
async: false,
contentType: false,
type: 'post',
progress: function (value) {
layer.msg(value);
},
success: function (res) {
console.log('阿里云上传结束');
if (res.code == '1') {
resolve(res.data);
} else {
layer.close(indexs);
reject({errorCode:api.errorCode.rejected,msg:res.msg});
}
},
fail:function (res) {
reject({errorCode:api.errorCode.networkAnomaly});
}
});
})
}
function savefile(savefiledata,type) {
return new Promise(function (resolve,reject) {
let savefileUrl = '/service/upload/tempsavefile';
if(type === '02'){
savefileUrl = '/service/upload/savevideofile';
}
api.request(savefileUrl, savefiledata).then(function (result) {
resolve(result.data);
}).catch(function (result) {
reject(result);
});
})
}