我是靠谱客的博主 超级音响,最近开发中收集的这篇文章主要介绍JS任意截图并上传图片,上传视频、上传文件,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

**

JS截图上传图片

**
在前端WEB开放过程中,经常使用上传图片、上传视频、上传音频以及上传其他文件等,通常都使用到各种上传插件,但是很多插件只是单纯的上传文件,不具备图片截图,即使有也很传统,今天我自己写了通过鼠标在图片进行绘制需要截图的矩形框便可以进行截图,很方便,很快捷,可以应用各种场景,比如轮播图只需要某个部分、头像截取、产品图,不需要PS重新设计图,上传图片后通过鼠标截取指定部分便可以截取想要的图片,同样具备视频上传预览,音频上传预览。如下图演示。
上传图片截图

上传图片截图
上传视频预览
上传音频预览

使用技术:使用了Vue(可有可无,就是简单事件操作,可以改成自己框架的使用方式)、ElementUI(进度条和按钮,可以改成自己框架的按钮样式)、原生POST网络请求XMLHttpRequest,技术没有的问题兄弟姐妹,可以把上传进度条改成Canvas绘制,我懒得改了,可以把上传哪里改成原生的

<style>
.clearfix {clear:both!important}
.tl{text-align:left}
.tc{text-align:center}
.tr{text-align:right}
.fl{float:left}
.fr{float:right}
.c_red {color: red}
.f14{font-size: 14px}
.cursor{cursor:pointer}
</style>
<div class="clearfix" style="position: relative;overflow: hidden;">
    <div class="fl" style="width: 600px;">
   		<div style="padding: 16px">
   			<div style="background: url('{__static__}/image/bg.png');position: relative;height: 568px;width: 100%">
   				<canvas id="canvas" width="568px" height="568px" style="background: #fff;position: relative;z-index: 800">抱歉,您的浏览器不支持canvas元素</canvas>
   				<div v-if="is_show == true" style="position: absolute;z-index: 1000;top: 0px;left: 0px;background: rgba(0,0,0,0.5);width: 100%;height: 573px;text-align: center;">
   					<div style="margin-top: 230px">
   						<!-- element ui 进度条 -->
   						<el-progress type="circle" :stroke-width="8" text-color="FFFFFF" :percentage="progress"></el-progress>
   					</div>
   				</div>
   			</div>
   		</div>
    </div>
    <div class="fl" style="width: calc(100% - 600px) !important;">
		<div class="tc" style="padding-top: 16px;padding-right: 16px;">
   			<div class="tl" style="position: relative;width: 100%;height: 183px;cursor: pointer;overflow: hidden;background: url('{__static__}/image/bg.png')">
   				<img id="img" src="" @click="showBigImg">
   			</div>
   			<div style="position: relative !important;width: 100% !important;padding-top: 14px">
   				<div>
	   				<a href="javascript:;" class="loadingfile" style="width: 159px;border-radius: 0px">
						选择文件<input type="file" value="" class="head">
					</a>
   				</div>
   				<div class="tl" style="line-height: 32px">
   					<span>图片压缩:</span>
   					<span></span>
   					<input type="radio" name="isCs" value="1" />
   					<span></span>
   					<input type="radio" name="isCs" value="2" checked="checked"/>
   				</div>
   			</div>
   			<div class="f14 c_red tl" style="width: 100%;padding-top: 6px;line-height: 24px">
				点击选择文件按钮,上传图片后在左边图片上,按住鼠标左键移动画出需要上传的指定位置图片,无任何操作将原图上传,该截图功能只支持图片上传
   			</div>
		</div>
    </div>
</div>
<div class="tpl-botton" style="bottom: 0px;text-align: right;padding-top: 6px;padding-bottom: 2px;padding-right: 6px">
	<el-button type="primary" @click="onSave()">立即上传</el-button>
 	<el-button style="width:105px" onclick="closeHead()">取消</el-button>
</div>
<script type="text/javascript">
var form 	= null;
var imgurl  = "";
var fileData= null;
var imgbase = null;
var vue = new Vue({
    el: "#dcappm",
    data() {
        return {
        	progress: 0,
        	is_show: false,
        }
    },
    created() {
    	window.is_show = this.is_show;
    },
    methods: {
        //保存
    	onSave(){
    		var _this = this;
    		if(this.is_show){
    			parent.erro("文件正在上传中,请稍后操作!");
    			return;
    		}
    		if(!fileData){
    			parent.erro("请上传文件!");
    			return;
    		}
    		if(imgbase == null){
    			if(isCheck() == 1){
        			initCompression(imgurl, function(){
        				_this.upload();
    				});
        		}else{
        			form 	= new FormData();
           	    	form.append("file", fileData);
           	    	_this.upload();
        		}
    		}else{
    			//组装上传参数
    	    	if(isCheck() == 1){
    	    		initCompression(imgbase, function (){
    	    			_this.upload();
    	    		});
    	    	}else{
    	    		var file 	= blobToFile(imgbase, fileData.name);
    	    	    form 		= new FormData();
    	        	form.append("file", file);
    	        	_this.upload();
    	    	}
    		}
    	},
    	//上传
    	upload(){
    		var _this = this;
    		this.is_show = true;
    		HttpClient({
    			url:  "{__app__}/v1/upload/load", //上传地址
    			type: "POST",
    			data: form,
    			success: function(data){
    				_this.progress = 0;
    				_this.is_show  = false;
    				localStorage.setItem("XFROM_UPLOAD_IMG", JSON.stringify(data.list));
    				initView();
    				parent.closeformdia(data.msg);
    			},
    			progress: function(progress){
    				_this.progress = Math.ceil(progress);
    			},
    			error: function(error){
    				parent.erro(error);
    			}
    		});
    	},
    	showBigImg(val){
    		//预览大图,自己实现该功能
    		parent.openWord(val.target.currentSrc);
    	}
    }
});
var canvas 	= document.getElementById("canvas");
if (canvas.getContext) {
    var context = canvas.getContext('2d');  //2d用单引用括起来
}
//绘制
canvas.drawing = function (x1, y1, x2, y2, e) {
    let self = this;
    if (!context) {
        return;
    } else {
        // 设置画笔的颜色和大小
        context.fillStyle 	= "red";  // 填充颜色为红色
        context.strokeStyle = "#FF00E4";  // 画笔的颜色
        context.lineWidth 	= 2;  // 指定描边线的宽度

        context.save();
        context.beginPath();

       if (self.strokeRectFlag) {
            // console.log('画空心矩形')
            self.initCanvas();
            if (e.shiftKey === true) {
                // 正方形
                let d = ((x2 - x1) < (y2 -y1)) ? (x2 - x1) : (y2 - y1);
                context.strokeRect(x1, y1, d, d);
            } else {
                // 普通方形
                context.strokeRect(x1, y1, x2 - x1, y2 - y1);
            }
        } else if (self.strokeCircelFlag) {
            // console.log('画空心圆形')
            self.initCanvas();
            let k = ((x2 - x1) / 0.55);
            let w = (x2 - x1) / 2;
            let h = (y2 - y1) / 2;

            if (e.shiftKey === true) {
                // circle
                let r = Math.sqrt(w * w + h * h);
                context.arc(w + x1, h + y1, r, 0, Math.PI * 2);
            } else {
                // bezier double ellipse algorithm
                context.moveTo(x1, y1 + h);
                context.bezierCurveTo(x1, y1 + h * 3, x1 + w * 11 / 5, y1 + h * 3, x1 + w * 11 / 5, y1 + h);
                context.bezierCurveTo(x1 + w * 11 / 5, y1 - h, x1, y1 - h, x1, y1 + h);
            }
            context.stroke();
        }
        context.restore();
        context.closePath();
    }
};
//按下鼠标
canvas.onmousedown = function mouseDownAction(e) {
    let self 	= this;
    self.X1 	= e.offsetX;
    self.Y1 	= e.offsetY;
    self.isMouseDown = true;
    //self.loadImage();
};
//移动鼠标
canvas.onmousemove = function mouseMoveAction(e) {
    let self 	= this;
    if (self.isMouseDown) {
        self.X2 = e.offsetX;
        self.Y2 = e.offsetY;
        self.drawing(self.X1, self.Y1, self.X2, self.Y2, e);
    }
};

//鼠标抬起
canvas.onmouseup = function mouseUpAction(e) {
    let self = this;
    self.lastImage = canvas.toDataURL('image/png');
    self.isMouseDown = false;

    if((e.offsetX - self.X1) > 0 && (e.offsetY - self.Y1) > 0){
	    //生成切片图片
	    var cvas 	= document.createElement('canvas')
	    var ctt 	= cvas.getContext('2d');
	    var imgs 	= new Image();
	    imgs.crossOrigin = 'Anonymous';
	    imgs.src 	= imgurl;
	    imgs.onload = function() {
	    	//第一次坐标点
	    	var X1 		= self.X1;
	    	var Y1 		= self.Y1;
	    	//最后坐标点
	    	var X2 		= e.offsetX;
	    	var Y2 		= e.offsetY;

	    	if(this.width > this.height){
		    	var pifx 	= (this.width / canvas.width);
		    	var newH 	= (this.height / pifx);
		    	var tranY 	= (canvas.height - newH) / 2; //平移点
	        	//图片上起始真实坐标点
	        	img_x1  	= X1 * pifx;
	        	img_y1 		= (Y1 - tranY) * pifx;
	        	//图片上最后真实坐标点
	        	img_x2  	= X2 * pifx;
	        	img_y2 		= (Y2 - tranY) * pifx;
				//图片的长宽
	        	var img_w 	= img_x2 - img_x1;
	        	var img_h 	= img_y2 - img_y1;
				//绘制图片
				cvas.width 	= img_w;
	        	cvas.height = img_h;
	        	ctt.drawImage(imgs, img_x1, img_y1 , img_w , img_h , 0 , 0 , cvas.width , cvas.height);
	    	}else if(this.width < this.height){
	    		var pifx 	= (this.height / canvas.height);
		    	var newW 	= (this.width / pifx);
		    	var tranX 	= (canvas.width - newW) / 2; //平移点
		    	//图片上起始真实坐标点
	        	img_x1  	= (X1 - tranX) * pifx;
	        	img_y1 		= Y1 * pifx;
	        	//图片上最后真实坐标点
	        	img_x2  	= (X2 - tranX) * pifx;
	        	img_y2 		= Y2 * pifx;
				//图片的长宽
	        	var img_w 	= img_x2 - img_x1;
	        	var img_h 	= img_y2 - img_y1;
				//绘制图片
				cvas.width 	= img_w;
	        	cvas.height = img_h;
	        	ctt.drawImage(imgs, img_x1, img_y1 , img_w , img_h , 0 , 0 , cvas.width , cvas.height);
	    	}else{
	    		var pifx 	= (this.height / canvas.height);
		    	//图片上起始真实坐标点
	        	img_x1  	= X1 * pifx;
	        	img_y1 		= Y1 * pifx;
	        	//图片上最后真实坐标点
	        	img_x2  	= X2 * pifx;
	        	img_y2 		= Y2 * pifx;
				//图片的长宽
	        	var img_w 	= img_x2 - img_x1;
	        	var img_h 	= img_y2 - img_y1;
				//绘制图片
				cvas.width 	= img_w;
	        	cvas.height = img_h;
	        	ctt.drawImage(imgs, img_x1, img_y1 , img_w , img_h , 0 , 0 , cvas.width , cvas.height);
	    	}
	    	//显示截图
	    	var cutImgUrl = cvas.toDataURL('image/png');
	    	imgbase 	= cutImgUrl;
	    	initShows(cutImgUrl);
	    }
    }
};
//加载绘制
canvas.loadImage = function () {
    let self 	= this;
    let img 	= new Image();
    img.crossOrigin = 'Anonymous';
    img.src 	= self.lastImage;
    context.drawImage(img, 0, 0, canvas.width, canvas.height);
};
//初始化
canvas.initCanvas = function () {
    context.clearRect(0, 0, canvas.width, canvas.height);
    //canvas.loadImage();
};

//上传请求
var HttpClient = function (param){
	var xmlHttp = null;
	if (window.XMLHttpRequest){
		xmlHttp = new XMLHttpRequest();
	}else if (window.ActiveXObject){
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if(xmlHttp != null){
		if(param.type == null){
			param.error("请求类型错误!");
			return;
		}
		xmlHttp.onload = function() {
		    if (this.status == 200) {
		      	var data = JSON.parse(this.response);
				param.success(data);
		    };
		};
		xmlHttp.upload.onprogress = function(e) {
	        if (e.lengthComputable) {
				var percentComplete = (e.loaded / e.total) * 100;
				param.progress(percentComplete);
	        }
	    };
	    xmlHttp.onerror = function(e) {
			param.error(e);
	    };
		//xmlHttp.timeout = 1000*60*20;
		xmlHttp.ontimeout = function () {
			param.error("请求超时");
		}
		if(param.type == "GET" || param.type == "get"){
			xmlHttp.open("GET", param.url, true);//true 异步
		}else{
			xmlHttp.open("POST", param.url, true);
		}
		xmlHttp.setRequestHeader('AUTH-TOKEN', localStorage.getItem("xform_token"));
		xmlHttp.send(param.data);
	}else{
		param.error("请求不支持");
	}
}

//Radio选择值
var isCheck = function (){
	var temp = document.getElementsByName("isCs");
	var value = 1;
	for(var i=0; i < temp.length; i++) {
		if(temp[i].checked){
			value = temp[i].value;
			break;
		}
	}
	return value;
}

//blob流转file
var blobToFile = function (dataurl, fileName){
   	var arr = dataurl.split(','),
       mime = arr[0].match(/:(.*?);/)[1],
       bstr = atob(arr[1]),
       n 	= bstr.length,
       u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    var file = new File([u8arr], fileName, {type: mime});
    file.lastModifiedDate = new Date();
    return file;
};

//图片压缩
var initCompression = function(csImg, success){
	var csCanvas 	= document.createElement('canvas')
    var csContext 	= csCanvas.getContext('2d');
    var csImage 	= new Image();
    csImage.crossOrigin = 'Anonymous';
    csImage.src 	= csImg;
    csImage.onload 	= function() {
    	// 图片原始尺寸
    	var originWidth = this.width;
    	var originHeight= this.height;
    	// 最大尺寸限制
    	var maxWidth 	= 720;
    	var maxHeight 	= 480;
    	// 目标尺寸
    	var targetWidth = originWidth;
    	var targetHeight= originHeight;
    	// 图片尺寸超过设置的限制
    	if (originWidth > maxWidth || originHeight > maxHeight) {
    		if (originWidth / originHeight > maxWidth / maxHeight) {
    			targetHeight 	= maxHeight;
    			targetWidth 	= Math.round(maxHeight * (originWidth / originHeight));
    		} else {
    			targetWidth 	= maxWidth;
    			targetHeight 	= Math.round(maxWidth * (originHeight / originWidth));
    		}
    	}
    	//canvas对图片进行缩放
    	csCanvas.width 		= targetWidth;
    	csCanvas.height 	= targetHeight;
    	csCanvas.style.background = "rgba(0,0,0,0)";
    	// 清除画布
    	csContext.clearRect(0, 0, targetWidth, targetHeight);
    	// 图片压缩
    	csContext.drawImage(csImage, 0, 0, targetWidth, targetHeight);
    	var csImgURL 	    = csCanvas.toDataURL('image/jpeg', 1);
    	//组装上传参数
	    var file 			= blobToFile(csImgURL, fileData.name);

	    form 				= new FormData();
    	form.append("file", file);

    	if(success){
    		success();
    	}
    }
};

//显示右边小图
var initShows = function(imgurl){
	//生成切片图片
    var imgs 	= new Image();
    imgs.crossOrigin = 'Anonymous';
    imgs.src 	= imgurl;
    var cut    	= document.getElementById("img");
    cut.style   = "";
    var setWH   = 183;
    imgs.onload = function() {
    	// 图片原始尺寸
    	var originWidth = this.width;
    	var originHeight= this.height;
    	if(originWidth > originHeight){
    		var pifx 			= (this.width / setWH);
	    	var newH 			= (this.height / pifx);
	    	cut.style.marginTop = (setWH - newH) / 2 + "px";
    		cut.style.width 	= "100%";
    	}else if(originWidth < originHeight){
    		var pifx 			= (this.height / setWH);
	    	var newW 			= (this.width / pifx);
	    	cut.style.marginLeft= (setWH - newW) / 2 + "px";
    		cut.style.height 	= "100%";
    	}else{
    		cut.style.width 	= "100%";
    		cut.style.height 	= "100%";
    	}
       	cut.src    			= imgurl;
    }
};

//初始化绘图
var initDraw = function (flag) {
	context.globalAlpha 		= 1;
    canvas.strokeRectFlag 		= false;
    canvas.strokeCircelFlag 	= false;
    canvas[flag] 				= true;
    // 设置鼠标样式,默认画笔,如果
    canvas.style.cursor 		= "url({__static__}/image/paintbrush.png) 0 0, default";
    if (canvas.eraserFlag) {
        canvas.style.cursor 	= "url({__static__}/image/eraser-20.png) 10 10, default";
    }
    //添加图片
    canvas.style.background 	= "url("+imgurl+")";
    canvas.style.backgroundRepeat = "no-repeat";

    var imgs 					= new Image();
    imgs.crossOrigin 			= 'Anonymous';
    imgs.src 					= imgurl;
    imgs.onload = function() {
    	if(this.width > this.height){
	    	var pifx 			= (this.width / canvas.width);
	    	var newH 			= (this.height / pifx);
	    	canvas.style.backgroundPositionY 	= (canvas.height - newH) / 2 + "px";
    		canvas.style.backgroundSize 		= "100% " + newH + "px";
    	}else if(this.width < this.height){
    		var pifx 			= (this.height / canvas.height);
	    	var newW 			= (this.width / pifx);
	    	canvas.style.backgroundPositionX 	= (canvas.width - newW) / 2 + "px";
    		canvas.style.backgroundSize 		= newW + "px 100%";
    	}else{
    		canvas.style.backgroundSize 		= "100% 100%";
    	}
    }
};

//视频预览
var video 	 = document.createElement('video');
var interval = null;
var initVideo = function(){
	context.globalAlpha 			= 1;
    canvas.style.backgroundRepeat 	= "no-repeat";
    canvas.style.backgroundSize 	= "100% 100%";

	/* video.setAttribute("controls","controls");
	video.setAttribute("autoplay","autoplay");
	video.setAttribute("loop","loop");
	video.setAttribute("style","width:568px;height:586px"); */

	video.controls 	= false;
	video.loop 		= true;
	video.autoplay 	= true;
	video.src   	= imgurl;
	video.addEventListener('play',function(e){
		var width 	= e.target.videoWidth;
		var height 	= e.target.videoHeight;
		//1000/25=40
		interval = window.setInterval(function(){
        	if(width > height){
    	    	var pifx 			= (width / canvas.width);
    	    	var newH 			= (height / pifx);
    	    	var tranH 			= (canvas.height - newH) / 2
    	    	context.drawImage(video, 0, tranH, canvas.width, newH);
        	}else if(width < height){
        		var pifx 			= (height / canvas.height);
    	    	var newW 			= (width / pifx);
    	    	var tranX 			= (canvas.width - newW) / 2
    	    	context.drawImage(video, tranX, 0, newW, canvas.height);
        	}else{
        		context.drawImage(video, 0, 0, canvas.width, canvas.height);
        	}

        }, 40);
    });
	video.addEventListener('pause',function(){
        //clearInterval(interval);
    })
}

//上传音频预览
var audio 			= new Audio();
var initAudio = function (){
	context.globalAlpha = 1;
	audio 			 = new Audio();
	audio.controls 	 = false;
	audio.loop 		 = true;
	audio.autoplay 	 = true;
	audio.src   	 = imgurl;

	var AudioContext = window.AudioContext || window.webkitAudioContext;
	var audioContext = new AudioContext();
	var analyser 	 = audioContext.createAnalyser();
	analyser.fftSize = 256;
	analyser 		 = audioContext.createAnalyser();

	var audioSrc 	 = audioContext.createMediaElementSource(audio);
	audioSrc.connect(analyser);
	analyser.connect(audioContext.destination);

	context.lineWidth= 2;
	var grd 		 = context.createLinearGradient(0, 0, 600, 0);
	grd.addColorStop(0, "#30EE20");
	grd.addColorStop(1, "#EE2020");

	var grd2 		 = context.createLinearGradient(0, 0, 600, 0);
	grd2.addColorStop(0, "#30EE20");
	grd2.addColorStop(1, "#EE2020");

	var het 		 = 0;
	interval = window.setInterval(function(){
		context.clearRect(0, 0, canvas.width, canvas.height);
	    var dataArray = new Uint8Array(analyser.frequencyBinCount);
	    analyser.getByteFrequencyData(dataArray);
	    context.beginPath();
	    //568px
	    for (var i = 0; i < 50; i++) {
	        var value = dataArray[6*i];
	        context.fillStyle = grd;
	        context.fillRect(i * 11.36, 284, 10, -value + 1);
	        context.fillRect(i * 11.36, 280 - value, 1, het);
	        context.fillStyle = grd2;
	        context.fillRect(i * 11.36, 284, 10, value + 1);
	        context.fillRect(i * 11.36, 320 + value, 1, het);
	    }
    }, 1000 / 60);
}

//其他格式上传预览,可以自己开发
var initOther = function(){
	context.globalAlpha 	= 1;
	context.fillStyle 		= "#ffffff";
	context.fillRect(0, 0, canvas.width, canvas.height);
	context.font 			= "30px Arial";
	var x 					= (canvas.width / 2) - 100;
	var y 					= (canvas.height / 2) - 10;

	// 创建渐变
	var gradient 			= context.createLinearGradient(0, 0, canvas.width, 0);
	gradient.addColorStop("0", "magenta");
	gradient.addColorStop("0.5", "blue");
	gradient.addColorStop("1.0", "red");

	// 用渐变填色
	context.strokeStyle 	= gradient;
	context.strokeText("暂 不 支 持 预 览", x, y);
}

//初始化canvas
var initView = function () {
	//关闭视频
	if(video.playing){
		video.pause();
	}
	if(video){
		video.pause();
	}
	//关闭音频
	if(audio){
		audio.pause();
	}
	//清除定时器
	for(var n = 0; n <= interval; n++){
		clearInterval(n);
	}
	canvas.style.background = "url('')";
	context.globalAlpha = 0;
	context.restore();
    //context.closePath();
	context.clearRect(0, 0, canvas.width, canvas.height);
}

//关闭
var closeHead = function () {
	if(is_show){
		parent.erro("图片正在上传中,请稍后操作!");
		return;
	}
	initView();
	parent.closeformdia(); //关闭弹出
}

//上传文件
var file 			= document.querySelector('.head'); //document.getElementById('file');
file.onchange 		= function() {
    fileData 		= this.files[0];//这是我们上传的文件
    var reader 		= new FileReader();
    reader.readAsDataURL(fileData);//异步读取文件内容,结果用data:url的字符串形式表示
    /*当读取操作成功完成时调用*/
    reader.onload	= function(e) {
    	initView();
    	imgurl 		= this.result;
    	var type 	= fileData.type;
    	var suffix 	= type.split("/");
    	if(suffix[0] == "image"){
    		initShows(imgurl);
    		//方框
            initDraw("strokeRectFlag");
    		//圆框
          	//initDraw("strokeCircelFlag");
    	}else if(suffix[0] == "video"){
    		initShows("{__static__}/icon/error2.png");
    		//视频
    		initVideo();
    	}else if(suffix[0] == "audio"){
    		initShows("{__static__}/icon/error2.png");
    		//音频
    		initAudio();
    	}else{
    		initShows("{__static__}/icon/error2.png");
			//其他
    		initOther();
    	}
    }
}
</script>
<?php
/**
 * 上传文件控制器
 */
class UploadController extends Controller {

    /**
     * 上传所有文件
     */
    public function load(){
        $allowFiles = array(".xls", ".xlsx", ".doc", ".docx", ".png", ".jpg", ".jpeg", ".gif", ".wav", ".mp4", ".3gp", ".mp3", ".avi", ".zip", ".rar", ".7z");
        $upload = new Upload($_FILES, $allowFiles, 200);
        $upload->save();
    }
}
<?php
/**
 * 上传文件类
 */
class Upload {

    //上传文件句柄
    private $files      = [];
    //上传文件路径
    private $dirpath    = __UPLOAD__ . "/data/uploads";
    //上传文件最大
    private $fileSize   = 100 * 1024 * 1024; //默认100M  1MB=1024KB=1048576 Byte字节
    //允许上传文件类型
    private $allowFiles = [".png", ".jpg", ".jpeg", ".gif", ".xls", ".xlsx" , ".zip", ".mp4", ".3gp", ".mp3", ".avi", ".doc", ".docx"];

    /**
     * 构造函数
     * @param unknown $fileList 上传文件清单
     * @param unknown $allowFiles 上传后缀名限制
     * @param number $fileSize 上传文件大小限制 单位:MB
     */
    public function __construct($fileList, $allowFiles = null, $fileSize = 0){
        $this->files = $fileList;
        if(!empty($allowFiles) && is_array($allowFiles)){
            $this->allowFiles   = array_merge($this->allowFiles, $allowFiles);
        }
        if(!empty($fileSize) && $fileSize > 0){
            $this->fileSize     = $fileSize * 1024 * 1024;
        }
    }

    /**
     * 删除文件
     * @param unknown $path
     */
    public function delete($path){
        $unfile = $path;
        if(is_file($path)){
            unset($unfile); //解除文件占用
            @unlink($path);
        }
    }

    /**
     * 上传文件
     * @param unknown $fileList $_FILE;
     * @return unknown
     */
    public function save(){
        if(empty($this->files)){
            $this->show(-1, "上传文件不存在");
        }
        $value          = array();
        foreach ($this->files as $file){
            if(!file_exists($file['tmp_name'])){
                $this->show(-2, "上传文件不存在");
            }
            if (!is_uploaded_file($file['tmp_name'])) {
                $this->show(-2, "文件上传错误");
            }

            $fileName    = $file['name'];
            $fileSize    = $file['size'];
            $fileExt     = strtolower(strrchr($fileName, '.'));
            $newPath     = date("Ymd");
            $newName     = Regular::getRandStr(12).date("YmdHis");

            //文件完整路径
            $path        = $this->dirpath."/".$newPath."/".$newName.$fileExt;

            if($fileSize > $this->fileSize){
                $this->show(-3, "上传文件大小超过了限制");
            }

            if(!in_array($fileExt, $this->allowFiles)){
                $this->show(-4, "不支持该格式文件上传");
            }

            File::createDir($this->dirpath."/".$newPath);
            if (!file_exists($this->dirpath."/".$newPath) && !chmod($this->dirpath."/".$newPath, 0777)) {
                $this->show(-5, "目录创建失败");
            } else if (!is_writeable($this->dirpath."/".$newPath)) {
                $this->show(-6, "目录没有写权限");
            }

            if (!(@move_uploaded_file($file["tmp_name"], $path) && file_exists($path))) {
                $this->show(-7, "文件创建失败");
            } else {
                //文件创建成功
                if($this->prefixType($fileExt) == "image"){
                    //木马检测
                    if(!$this->check_illegal($path)){
                        @unlink($path);
                        $this->show(-101, "文件上传异常,图片格式不正确");
                    }
                }
                $value[] = array(
                    "file_id"   => md5($newName),
                    "title"     => $newName,
                    "original"  => $fileName,
                    "url"       => "data/uploads/".$newPath."/".$newName.$fileExt,
                    "type"      => $this->prefixType($fileExt),
                    "size"      => $fileSize
                );
            }
        }
        $this->show(0, "上传成功", $value);
    }

    /**
     * 输出信息
     * @param unknown $code
     * @param unknown $msg
     * @param unknown $data
     */
    private function show($code, $msg, $data = null) {
        $arr = array(
            "code"  => $code,
            "msg"   => $msg,
        );
        if(!empty($data)){
            $arr["list"] = $data;
        }
        echo json_encode($arr, JSON_UNESCAPED_UNICODE);
        exit();
    }

    /**
     * # 检测图片是否含有木马
     * @param string $image 图片地址
     * @return bool
     */
    private function check_illegal($image) {
        if (file_exists($image)) {
            $resource = fopen($image, 'rb');
            $fileSize = filesize($image);
            fseek($resource, 0);
            if ($fileSize > 512) { // 取头和尾
                $hexCode = bin2hex(fread($resource, 512));
                fseek($resource, $fileSize - 512);
                $hexCode .= bin2hex(fread($resource, 512));
            } else { // 取全部
                $hexCode = bin2hex(fread($resource, $fileSize));
            }
            fclose($resource);
            if (preg_match("/(3c25)|(3c3f.*?706870)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)/is", $hexCode)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 自定义文件类型
     * @param unknown $prefix
     * @return string
     */
    private function prefixType($prefix) {
        //图片
        $array1 = [".jpg",".png",".jpeg",".gif"];
        if(in_array($prefix, $array1)) {
            return "image";
        }
        //文档
        $array2 = [".doc",".docx"];
        if(in_array($prefix, $array2)) {
            return "doc";
        }
        //表格
        $array3 = [".xls",".xlsx"];
        if(in_array($prefix, $array3)) {
            return "excel";
        }
        //视频
        $array4 = [".mp4",".avi",".asf",".mov",".wmv",".3gp",".rm",".rmvb",".flv",".f4v"];
        if(in_array($prefix, $array4)) {
            return "video";
        }
        //音乐
        $array5 = [".mp3",".mpeg-4",".midi",".wma",".vqf",".amr",".ape",".flac",".aac"];
        if(in_array($prefix, $array5)) {
            return "music";
        }
        //压缩包 7z、CAB、ARJ、LZH、TAR、GZ、ACE、UUE、BZ2、JAR、ISO
        $array6 = [".zip",".rar"];
        if(in_array($prefix, $array6)) {
            return "zip";
        }
        return "other";
    }
}

资源图片
鼠标样式图paintbrush.png
无预览图片error2.png
背景图
橡皮擦图片

最后

以上就是超级音响为你收集整理的JS任意截图并上传图片,上传视频、上传文件的全部内容,希望文章能够帮你解决JS任意截图并上传图片,上传视频、上传文件所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部