上传图片使用formdata请求接口传值

后台上传图片使用formdata请求接口传值

后台管理系统开发过程中经常遇到上传图片的问题,那么这种情况下多数通过formdata传值给后台
传值格式例如:

let formData=new FormData();
		formData.append('userId',11604);
		formData.append('money','TWD');
//"file":后台接=接收的字段名
//file:要提交的数据
		$.ajax({
	        url:****
	        type:'POST',
	        data:formData,
	        cache:false,
	        processData:false,
	        contentType:false,
	        success:function(data){
	          console.log(data);
	        },
	        error:function(error){
	          console.log(error);
	        }
	    })

那么还有一种情况是多图片传值
html如下:

<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta name="description" content="OTC Admin " />
	<meta name="author" content="" />
	<title></title>
	<script src="../js/jquery-1.11.1.min.js"></script>
	<style type="text/css">
		.release_up_pic .up_pic {
			background-color: #fff;
			padding: 15px 12px;
			font-size: 0;
			padding-bottom: 3px;
			border-bottom: 1px solid #e7e7e7;
			border-top: 1px solid #e7e7e7;
		}
		.release_up_pic .up_pic .pic_look {
			width: 20%;
			height: 130px;
			display: inline-block;
			background-size: cover;
			background-position: center center;
			background-repeat: no-repeat;
			box-sizing: border-box;
			margin-left: 3.3333%;
			margin-bottom: 12px;
			position: relative;
		}
		.release_up_pic .up_pic .pic_look em {
			position: absolute;
			display: inline-block;
			width: 25px;
			height: 25px;
			background-color: #ff0000;
			color: #fff;
			font-size: 18px; 
			right: 5px;
			top: 5px;
			text-align: center;
			line-height: 22px;
			border-radius: 50%;
			font-weight: bold;
		}
		#chose_pic_btn {
			width: 20%;
			height: 130px;
			position: relative;
			display: inline-block;
			background-image: url(../images/add.png);
			box-sizing: border-box;
			background-size: 30px 30px;
			background-position: center center;
			background-repeat: no-repeat;
			border: 1px solid #dbdbdb;
			margin-left: 3.3333%;
			margin-bottom: 12px;
		}
		#chose_pic_btn input {
			position: absolute;
			left: 0px;
			top: 0px;
			opacity: 0;
			width: 100%;
			height: 100%;
		}
		.release_btn {
			padding: 0 24px;
			margin-top: 70px;
		}
		.release_btn button {
			width: 100%;
			background-color: #2c87af;
			font-size: 1.4rem;
			color: #fff;
			border: none;
			border-radius: 3px;
			height: 45px;
			outline: none;
		}
		.release_btn button.none_btn {
			background-color: #f2f2f2;
			color: #2c87af;
			border: 1px solid #2c87af;
			margin-top: 15px;
		}
	</style>
</head>
<body class="page-body">
	<div class="page-container">
		<div class="sidebar-menu toggle-others fixed">
			<div class="panel panel-default row">	
				<div class="col-sm-12" >
					<p style="color:#000;font-size: 20px;font-weight:500;
					">上传相关转账截图</p>
					<div class="release_up_pic">
						<div class="up_pic" id="up_pic">
							<span id="chose_pic_btn" style="">
								<input type="file" accept="image/*" />
							</span>	
						</div>
					</div>
					<button type="button" class="btn btn-success" id="submit">提交</button>
				</div>
			</div>
		</div>	
	</div>
	<script src="../js/bootstrap.min.js"></script>
	<script type="text/javascript" src="../js/localIMG.js"></script>
	<script type="text/javascript" src="../js/mobileBUGFix.mini.js"></script>
	<script type="text/javascript">
		var picArr = new Array();// 存储图片
		$('input:file').localResizeIMG({
			width:130,// 宽度
			quality: 1, // 压缩参数 1 不压缩 越小清晰度越低
			success: function (result) {
				console.log(result);
				var img = new Image();
				img.src = result.base64;
				var _str = "-"
				$('#chose_pic_btn').before(_str);
				var _i =  picArr.length;
				var imgFile = dataURLtoFile(result.base64);
				picArr[_i] = imgFile;
				// picArr[_i] = _i;
				// console.log(picArr)
				// picArr为图片路径传给后台
			}
		});
		function dataURLtoFile(dataurl, filename = 'file') {
		  let arr = dataurl.split(',')
		  let mime = arr[0].match(/:(.*?);/)[1]
		  let suffix = mime.split('/')[1]
		  let bstr = atob(arr[1])
		  let n = bstr.length
		  let u8arr = new Uint8Array(n)
		  while (n--) {
		    u8arr[n] = bstr.charCodeAt(n)
		  }
		  return new File([u8arr], `${filename}.${suffix}`, {
		    type: mime
		  })
		}
		// 删除
		$(document).on('click', '#delete_pic', function(event) {
			var aa = $(this).parents(".pic_look").index();
			picArr.splice(aa,1);
			$(this).parents(".pic_look").remove();
			console.log(picArr);
		});	
		$("#submit").click(function(){
			var texxts=$("#textareas").val();
			console.log(texxts);
			console.log(picArr);
			let formData=new FormData();
			for(var i = 0; i < picArr.length;i++){
			    formData.append('file', picArr[i]);
			}
			
			
			$.ajax({
				url:"",
				type:'post',
				data:formData,
				cache:false,
				processData:false,
				contentType:false,
				success:function(data){
					console.log(data);
					var html = '';
					for (var i in data.list) {//类名pic_look不能删,这个是图片样式
						html += '+data.list[i].imgurl+'">' 
					};
					$('#up_pic').html(html); 
				},
				error:function(error){
				  console.log(error);
				}
			})
		});
	</script>
</body>
</html>

其中localIMG.js主要功能是将上传图片转化为base64,代码如下

**
     * 获得base64
     * @param {Object} obj
     * @param {Number} [obj.width] 图片需要压缩的宽度,高度会跟随调整
     * @param {Number} [obj.quality=0.8] 压缩质量,不压缩为1
     * @param {Function} [obj.before(this, blob, file)] 处理前函数,this指向的是input:file
     * @param {Function} obj.success(obj) 处理后函数
     * @example
     *
     */
    $.fn.localResizeIMG = function(obj) {
        this.on('change', function() {
            var file = this.files[0];
            var URL = window.URL || window.webkitURL;
            var blob = URL.createObjectURL(file);

            // 执行前函数
            if ($.isFunction(obj.before)) {
                obj.before(this, blob, file)
            };

            _create(blob, file);
            this.value = ''; // 清空临时数据
        });

        /**
         * 生成base64
         * @param blob 通过file获得的二进制
         */
        function _create(blob) {
            var img = new Image();
            img.src = blob;

            img.onload = function() {
                var that = this;

                //生成比例
                var w = that.width,
                    h = that.height,
                    scale = w / h;
                w = obj.width || w;
                h = w / scale;

                //生成canvas
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                $(canvas).attr({
                    width: w,
                    height: h
                });
                ctx.drawImage(that, 0, 0, w, h);

                /**
                 * 生成base64
                 * 兼容修复移动设备需要引入mobileBUGFix.js
                 */
                var base64 = canvas.toDataURL('image/jpeg', obj.quality || 0.8);

                // 修复IOS
                if (navigator.userAgent.match(/iphone/i)) {
                    var mpImg = new MegaPixImage(img);
                    mpImg.render(canvas, {
                        maxWidth: w,
                        maxHeight: h,
                        quality: obj.quality || 0.8
                    });
                    base64 = canvas.toDataURL('image/jpeg', obj.quality || 0.8);
                }

                // 修复android
                if (navigator.userAgent.match(/Android/i)) {
                    var encoder = new JPEGEncoder();
                    base64 = encoder.encode(ctx.getImageData(0, 0, w, h), obj.quality * 100 || 80);
                }

                // 生成结果
                var result = {
                    base64: base64,
                    clearBase64: base64.substr(base64.indexOf(',') + 1)
                };

                // 执行后函数
                obj.success(result);
            };
        }
    };


    // 例子
    /*
    $('input:file').localResizeIMG({
        width: 100,
        quality: 0.1,
        //before: function (that, blob) {},
        success: function (result) {
            var img = new Image();
            img.src = result.base64;

            $('body').append(img);
            console.log(result);
        }
    });
*/

那么这次和php后台合作,不想转化成base64,那么再封装一个base64转化为图片路径的方法如下

function dataURLtoFile(dataurl, filename = 'file') {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let suffix = mime.split('/')[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime
  })
}

然后这样就可以传给后台想要的数据了。

你可能感兴趣的:(前端,jquery)