同步/异步 上传oss整理 图片 音频 视频

上传整个流程(图片上传需要截图)
裁剪:


上传插件:


弹窗:

文件下载地址:下载地址 提取码:agiw


html

图片裁剪

<div id="shear" style="display:none;width:800px;height: 400px;z-index: 99999999;">
    <img src="" id="shear_img" style="width:800px;height:400px;"/>
div>

同步/异步 上传oss整理 图片 音频 视频_第1张图片同步/异步 上传oss整理 图片 音频 视频_第2张图片

上传按钮布局

<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}}">&#x1006;</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">&#x1007;</i>
			<div class="hwaudio-animate"></div>
			<div><i>{{items.length}}</i>"</div>
		</div>
		{{# }); }}
	{{#  } }}
</div>

上传JS

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+'">ဆ'+ '
+this.result+'">
'
+ '
'
; 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('上传失败');
	})
})

WebUploader-上传到-oss

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);
}

上传oss

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});
            }
        });
    })
}

保存文件获得fileid

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);
        });
    })
}

打印出来的数据
同步/异步 上传oss整理 图片 音频 视频_第3张图片
接口所需要的结构
同步/异步 上传oss整理 图片 音频 视频_第4张图片
同步/异步 上传oss整理 图片 音频 视频_第5张图片同步/异步 上传oss整理 图片 音频 视频_第6张图片
同步/异步 上传oss整理 图片 音频 视频_第7张图片

你可能感兴趣的:(jquery)