上传图片之前先预览

本文转载自:https://www.cnblogs.com/tandaxia/p/5125275.html

由于最近项目中需要实现信息发布前的编辑整理功能,如下图:
在这里插入图片描述
找到的解决方案有:
1.直接使用bootstrap下的fileinpu插件,我看了很多,有需要的小伙伴可以参考:https://www.cnblogs.com/zhukaixin/p/9154903.html 来自:胖陀螺的春天;

但是我需要的只是简单的上传之前的预览功能,于是在 https://www.cnblogs.com/tandaxia/p/5125275.html 中发现

用html的file标签就能实现图片上传前预览,就是通过file标签和js的FileReader接口,把选择的图片文件调用readAsDataURL方法,把图片数据转成base64字符串形式显示在页面上。

上我项目中用到的代码:
页面上:

<div class="form-group"><label class="col-sm-2 control-label">封面图片:</label>
		<div class="col-sm-10"><input type="file" class="form-control file-loading" onChange="getimage(this)"></div>
</div>

JS:

<script type="text/javascript">            
            //判断浏览器是否支持FileReader接口
            if (typeof FileReader == 'undefined') {
				//若不支持则封面图片提示不可预览,但不影响上传
                document.getElementById("titleimage").src = "http://*.*.*.*/images/6.jpg";
            }

//选择图片,马上预览
function getimage(obj) {
	var file = obj.files[0];
	//判断文件类型
	if(file['type'] == 'image/jpg' || file['type'] == 'image/png' || file['type'] == 'image/jpeg' || file['type'] == 'image/gif')
	{
		var reader = new FileReader();
		//读取文件过程方法
		reader.onloadstart = function (e) {
			console.log("开始读取....");
		}
		reader.onprogress = function (e) {
			console.log("正在读取中....");
		}
		reader.onabort = function (e) {
			console.log("中断读取....");
		}
		reader.onerror = function (e) {
			console.log("读取异常....");
		}
		reader.onload = function (e) {
			console.log("成功读取....");

			var img = document.getElementById("titleimage");
			img.src = e.target.result;
			//或者 img.src = this.result;  //e.target == this
		}
		reader.readAsDataURL(file)
	}
	else
		alert("文件格式不支持,请重新选择!");
 }
以上就达到了我的需求,感谢! 以此仅纪录在项目中遇到的疑惑

猜你喜欢

转载自blog.csdn.net/KreaWu/article/details/88531200