jquery 实现图片上传,并在前端显示出来

时间:2021-02-08 14:19:15

目前遇到一个图片上上传的需求,突然发现,原来之前都没有做过此种类型的需求,以下是需求样式:

jquery 实现图片上传,并在前端显示出来

看到需求后之所以有点懵,是因为我接触到的文件上传,一般都是按钮类型的,例如以下这种:

jquery 实现图片上传,并在前端显示出来

深呼吸,好好想一下,整理整理思路:

1.需要有一个虚线框,这里为一个div元素

2.再有一个十字框(和文字说明一起,可以集成组合为一张图片),这里可以可以为一个img元素,这样:当没有上传图片时,显示默认图片,当上传了,显示上传的图片

3.要实现点击能够上传,需要有一个 input 元素:首先input元素不能显示出来,初步想了一下,有两种实现方法,一种是使用 label标签 加input元素(label 标签关联input,input影藏,label设置为与div 同样大小),另一种是使用input单标签,设置它的z-index层级在最上层,然后设置为行块元素即与div一般大小,然后设置input的 opacity 为0,即透明状态;

4.需要可以删除图片,那就在div里再加一个span 元素,点击span元素时,删除图片

得到以下html:

 <div class="chuans">
<img src="__INDEX__/img/ins/chuanzhenm.png" alt="" data-imgsrc="__INDEX__/img/ins/chuanzhenm.png">
<input class="uploadImg file1" type="file" name="file1" >
<span class="delx Hui-iconfont"></span>
</div>

全部html如下:

 <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="__INDEX__/css/header2.css">
<link rel="stylesheet" href="__INDEX__/css/1.0.8/iconfont.css">
<link rel="stylesheet" href="__INDEX__/css/ins/insinfo.css">
<script src="__INDEX__/js/common/jquery-1.7.2.min.js"></script>
<script src="__INDEX__/js/layer.js"></script>
<script src="__INDEX__/js/ins/insinfo.js"></script>
<title></title> </head>
<body>
{include file="common/header1"}
<div class="insbox">
<h3 class="institle"><span class="isnnei">提交商业投保资料</span> </h3>
<div class="nelist">
<ul class="inul yilei clearfix">
<div class="toleft"><span class="nming maohaos toyilei">手机号</span></div>
<div class="toright"><input type="text" class="xiangton shoujihao" name="shoujihao"></div>
</ul>
<ul class="inul yilei clearfix">
<div class="toleft"><span class="nming maohaos toyilei">发动机号</span></div>
<div class="toright"><input type="text" class="xiangton fadongjihao" name="fadongjihao"></div>
</ul>
<ul class="inul yilei clearfix">
<div class="toleft"><span class="nming maohaos toyilei">车架号</span></div>
<div class="toright"><input type="text" class="xiangton chejiahao" name="chejiahao"></div>
</ul>
<ul class="inul erlei clearfix">
<div class="toleft"><span class="nming maohaos toerlei">身份证正反面</span></div>
<div class="toright clearfix">
<div class="chuans"> <img src="__INDEX__/img/ins/chuanzhenm.png" alt="" data-imgsrc="__INDEX__/img/ins/chuanzhenm.png">
<input class="uploadImg file1" type="file" name="file1" >
<span class="delx Hui-iconfont"></span>
</div>
<div class="shangshili clearfix">
<div class="shuom">示例</div>
<div class="shulitu">
<img src="__INDEX__/img/ins/shilizhen.png" alt="" data-imgsrc="__INDEX__/img/ins/shilizhen.png">
</div>
</div>
</div>
</ul>
<ul class="inul erlei clearfix">
<div class="toleft"><span class="nming "></span></div>
<div class="toright clearfix">
<div class="chuans"> <img src="__INDEX__/img/ins/chuanfanmian.png" data-imgsrc="__INDEX__/img/ins/chuanfanmian.png" alt="">
<input class="uploadImg file2" type="file" name="file2" >
<span class="delx Hui-iconfont"></span>
</div>
<div class="shangshili clearfix">
<div class="shuom">示例</div>
<div class="shulitu">
<img src="__INDEX__/img/ins/shilifan.png " alt="">
</div>
</div>
</div>
</ul>
<ul class="inul erlei clearfix">
<div class="toleft"><span class="nming maohaos toerlei">自拍照</span></div>
<div class="toright clearfix">
<div class="chuans"> <img src="__INDEX__/img/ins/dianchuan.png" data-imgsrc="__INDEX__/img/ins/dianchuan.png" alt="">
<input class="uploadImg file3" type="file" name="file3" >
<span class="delx Hui-iconfont"></span>
</div>
<div class="shangshili clearfix">
<div class="shuom"><span class="kanshili"><span class="chsa Hui-iconfont"></span>查看示例</span></div>
<div class="shulitu"></div>
</div>
</div>
</ul> </div> <div class="btns">
<span class="tibtn">确定</span>
</div>
</div>
<script>
var otijiourl = "{:url('insorder/submitInsInfo')}";
</script>
</body>
</html>

根据以上的规则设置css样式:

 .insbox{
width:1200px;
position:relative;
margin:0 auto;
border:1px solid #333;
color:#333;
border-radius: 20px;
margin-bottom:150px;
}
.inul {
min-height:44px;
margin:20px 0;
} ul.inul>div{
float:left;
}
h3.institle{
background:#333;
color:#fff;
text-align: center;
height:78px;
border-top-left-radius:20px;
border-top-right-radius:20px;
position:relative;
width:100%;
display:flex;
align-items: center;
justify-content:center;
}
.isnnei{
background:url(../../img/ins/card.png)no-repeat 0 center;
background-size: 50px auto;
}
h3.institle span{
padding-left: 58px;
font-size: 22px;
letter-spacing: 3px;
font-weight: normal;
}
.toleft{
width:25%;
text-align: right;
}
.toright{
width:75%;
}
input.xiangton{
border:1px solid #eee;
border-radius: 3px;
width:290px;
height:42px;
text-indent: 10px;
}
.toyilei{
line-height:44px;
}
span.nming {
margin-right:40px;
position:relative;
}
.maohaos::after{
content:":";
display:inline;
position:absolute;
right:;
right:-10px; }
.erlei{
height:172px;
line-height:172px;
}
div.toright>div{
float:left;
}
div.chuans{
position:relative;
width:240px;
height:160px;
border-radius: 3px;
border:1px dashed #ccc;
margin-right: 44px;
overflow: hidden;
}
div.chuans img{
position:absolute;
max-width:238px;
left:;
right:;
top:;
bottom:;
margin:auto;
}
div.shangshili>div{
float:left;
}
div.shangshili {
height:160px;
position:relative;
}
div.shuom{
margin-right:10px;
}
div.shulitu{
width:242px;
height:100%;
position:relative;
}
div.shulitu img{
position:absolute;
max-width:240px;
left:;right:;
top:;bottom:;
margin:auto;
}
div.btns{
margin-top:180px;
margin-bottom:40px;
position:relative;
text-align: center;
}
span.tibtn{
padding:8px 30px;
background:#333;
border-radius: 5px;
color:#fff;
}
div.chuans{
line-height:30px;
}
input.uploadImg{
display: inline-block;
width: 100%;
height: 100%;
opacity:;
z-index:;
}
span.delx {
position:absolute;
top:5px;
right:5px;
z-index:;
font-size: 30px;
float:right;
display:none;
border-radius: 50%;
}
span.delx:hover{
background:#333;
color:#fff;
cursor:pointer;
}
div.shuom span.chsa {
color:#e5000c;
margin-right:10px;
font-size: 20px;
font-weight: normal;
}
div.shuom{
color:#1f5fc3;
font-size: 14px;
font-weight: bold;
}

得到如下的样式:

jquery 实现图片上传,并在前端显示出来

下面开始写js:

首先需要判断上传的图片格式,如果不是jpeg,jpg,png,bmp,则提示图片上传格式错误,需重新上传;如果格式正确,那就或者上传图片的地址,把当前div 下 img 的src 设置为此图片地址,即可达到显示图片的目的

 $("body").on("change","div.chuans input.uploadImg",function(){

         var reads = new FileReader();
var f = $(this).get(0).files[0];
var rep = /jpeg|png|gif|bmp/ig;
var gstyle = f.type.split("/")[1];
if(rep.test(gstyle)){
reads.readAsDataURL(f);
var that = this;
reads.onload = function(e) {
$(that).parent().find("img").attr("src",this.result)
};
}else{
layer.msg("图片格式不正确,请上传 jpeg|png|gif|bmp 格式的图片")
} });

以下是删除图片:

 $("body").on("click","span.delx",function(){
var odatasrc = $(this).parents(".chuans").find("img").data("imgsrc");
var osrc = $(this).parents(".chuans").find("img").attr("src");
$(this).parents(".chuans").find("img").attr("src",odatasrc);
$(this).hide();
$(this).parents(".chuans").find("input").val("");
});

图片上传时,这里突然遇到一个报错:

jquery 实现图片上传,并在前端显示出来

这个错误找了好久,都没有发现是哪里出了问题,代码是这样的:

 $.ajax({
type:"post",
url:otijiourl,
data:odata,
dataType: 'json', //返回值类型 一般设置为json
success:function(res){
console.log(res);
},error:function(){
console.log("后台处理错误");
}
})

看了半天,也没有发现是哪里错了

最后百度了一下,发现别人也遇到了这样的问题,原因是使用 jquery ajax 发送请求的时候,会默认把data中的数据进行序列化。只要不进行序列化,就可以了。如果不进行序列化,需要增加一个参数:processData,设置为 false

变更之后的ajax 请求代码如下:

 $.ajax({
type:"post",
url:otijiourl,
data:odata,
dataType: 'json', //返回值类型 一般设置为json
processData: false, // jQuery不要去处理发送的数据
success:function(res){
console.log(res);
},error:function(){
console.log("后台处理错误");
}
})

改完之后就ok 了

全部js 代码如下:大功告成

 $(function(){

     $("body").on("change","div.chuans input.uploadImg",function(){

         var reads = new FileReader();
var f = $(this).get(0).files[0];
var rep = /jpeg|png|gif|bmp/ig;
var gstyle = f.type.split("/")[1];
if(rep.test(gstyle)){
reads.readAsDataURL(f);
var that = this;
reads.onload = function(e) {
$(that).parent().find("img").attr("src",this.result)
};
}else{
layer.msg("图片格式不正确,请上传 jpeg|png|gif|bmp 格式的图片")
} }); $("body").on("mouseenter","div.chuans",function(){
var odatasrc = $(this).find("img").data("imgsrc");
var osrc = $(this).find("img").attr("src"); if(osrc.indexOf(odatasrc)==-1){
$(this).find("span.delx").show();
}
});
$("body").on("mouseleave","div.chuans",function(){
$(this).find("span.delx").hide();
}); $("body").on("click","span.delx",function(){
var odatasrc = $(this).parents(".chuans").find("img").data("imgsrc");
var osrc = $(this).parents(".chuans").find("img").attr("src");
$(this).parents(".chuans").find("img").attr("src",odatasrc);
$(this).hide();
$(this).parents(".chuans").find("input").val("");
}); $("body").on("click","span.tibtn",function(){
var odata = getchuancan();
console.log(odata);
if(jiancecanshu()){
$.ajax({
type:"post",
url:otijiourl,
data:odata,
dataType: 'json', //返回值类型 一般设置为json
// contentType: "application/x-www-form-urlencoded; charset=utf-8",
processData: false, // jQuery不要去处理发送的数据
success:function(res){
console.log(res);
},error:function(){
console.log("后台处理错误");
}
})
}
}); function getchuancan(){
var formData = new FormData();
var ojson = {}; ojson.oshouji =$.trim( $("input.shoujihao").val()); ojson.ofdji = $("input.fadongjihao").val();
ojson.ochjiah = $("input.chejiahao").val(); // ojson.ozhenm = $("input.file1").get(0).files[0];
// ojson.opfanm = $("input.file2").get(0).files[0];
// ojson.oshilm = $("input.file3").get(0).files[0]; ojson.ozhenm = document.querySelector("input.file1").files[0];
ojson.opfanm = document.querySelector("input.file2").files[0];
ojson.oshilm = document.querySelector("input.file3").files[0]; formData.append('oshouji', ojson.oshouji);
formData.append('ofdji', ojson.ofdji);
formData.append('ochjiah', ojson.ochjiah);
formData.append('ozhenm', ojson.ozhenm);
formData.append('opfanm', ojson.opfanm);
formData.append('oshilm', ojson.oshilm); return ojson;
return formData;
} function jiancecanshu(){
var oshouji = $.trim($("input.shoujihao").val());
var ofdji = $("input.fadongjihao").val();
var ochjiah = $("input.chejiahao").val();
var ozhenm = $("input.file1").val();
var opfanm = $("input.file2").val();
var oshilm = $("input.file3").val();
var ocan = 100; var canarr = [0,1,2,3,4,5,6];
if(oshouji.length==0){
ocan=0;
}else if(ofdji.length==0){
ocan=1;
}else if(ochjiah.length==0){
ocan=2;
}else if(ozhenm.length==0){
ocan=3;
}else if(opfanm.length==0){
ocan=4;
}else if(oshilm.length==0){
ocan=5;
}else if(!isPhone(oshouji)){
ocan=6;
} var arr=[
"手机号为空,请输入手机号",
"发动机号为空,请输入发动机号",
"车架号为空,请输入车架号",
"身份证正面照为空,请输入身份证正面照",
"身份证反面照为空,请输入身份证反面照",
"自拍照为空,请输入自拍照",
"手机号输入错误,请输入正确的手机号"
]; if(canarr.indexOf(ocan)!=-1){
console.log("ocan: "+ocan);
console.log(arr);
layer.msg(arr[ocan]);
return false;
}else{
return true;
} } //检测手机号码
function isPhone(phone) {
if (phone == null || phone == '') {
// layer.msg('请填写手机号码');
return false;
}
//验证号码
var phoneReg = /(^1[3|4|5|7|8|9]\d{9}$)|(^09\d{8}$)/ig;
if (!phoneReg.test(phone)) {
// layer.msg('请填写正确的手机号码');
return false;
} else {
return true;
}
};
})

得到的图片上传如下:

jquery 实现图片上传,并在前端显示出来

备注:之所以一开始有点懵,是因为对需求没有明确分析,认真分析之后,会发现其实都是些比较简单而且容易的功能。认真分析之后,才能把东西做出来

jquery 实现图片上传,并在前端显示出来的更多相关文章

  1. Jquery自定义图片上传插件

    1 概述 编写后台网站程序大多数用到文件上传,可是传统的文件上传控件不是外观不够优雅,就是性能不太好看,翻阅众多文件上传控件的文章,发现可以这样去定义一个文件上传控件,实现的文件上传的效果图如下: 2 ...

  2. jquery实现图片上传前本地预览

    <!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...

  3. jquery之图片上传

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  4. jQuery plugins 图片上传

    http://plugins.jquery.com/ 用到一下插件: magnific popup 看大图 jQuery File Upload 多文件上传 jQuery Rotate 图片旋转 gi ...

  5. ThinkPHP5与JQuery实现图片上传和预览效果

    内容正文 这篇文章主要为大家详细介绍了thinkphp上传图片功能,和jquery预览图片效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 先上效果图: html和js代码如下: <!DO ...

  6. 基于jquery实现图片上传本地预览功能

    一.原理 分为两步: 当上传图片的input被触发并选择本地图片之后获取要上传的图片这个对象的URL(对象URL),把对象URL赋值给事先写好的img标签的src属性即可把图片显示出来.在这里,我们需 ...

  7. JQuery实现 图片上传

    用到的文件,我都已经打包好了,自行下载: https://files.cnblogs.com/files/lguow/lib.rar 核心代码如下: <input type="hidd ...

  8. jquery实现图片上传前本地预览功能

    HTML <img id="pic" src="" > <input id="upload" name="fil ...

  9. jquery实现图片上传前的预览

    html代码 <div id="uploadPreview"></div> <input id="uploadImage" typ ...

随机推荐

  1. 数据结构算法C语言实现(七)--- 3&period;1栈的线性实现及应用举例

    一.简述 栈,LIFO.是操作受限的线性表,和线性表一样有两种存储表示方法.下面以顺序存储为例,实现. 二.ADT 暂无. 三.头文件 //3_1.h /** author:zhaoyu email: ...

  2. iframe跨域自适应高度

    思路: 现有主界面main在域a下,被嵌套页面B在域b下,被嵌套页面B又嵌套一个在域a下的中介页面A. 当用户打开浏览器访问mail.html的时候载入B,触发B的onload事件获取其自身高度,然后 ...

  3. 在Web上调用Ocx控件

    原文:http://blog.csdn.net/goodadult2012/article/details/6343369 在HTML页面中使用ActiveX控件包含三个基本操作:将控件放入HTML中 ...

  4. 使用intellij idea搭建MAVEN&plus;springmvc&plus;mybatis框架

    原文:使用intellij idea搭建MAVEN+springmvc+mybatis框架 1.首先使用idea创建一个maven项目 2.接着配置pom.xml,以下为我的配置 <projec ...

  5. ASP&period;NET输入文本框自动提示功能

    在ASP.NET Web开发中会经常用到自动提示功能,比如百度搜索.我们只要输入相应的关键字,就可以自动得到相似搜索关键字的提示,方便我们快速的输入关键字进行查询. 那么在ASP.NET中,如果我们需 ...

  6. supesite 模板相关文档记录

    文件说明:http://wenku.baidu.com/view/69c07820af45b307e87197ac.html 开发文档:http://wenku.baidu.com/view/35f6 ...

  7. CSS 背景 background 讲解

    背景语法:background: background-color || background-image || background-repeat || background-attachment ...

  8. docker时间和本地时间不一致的问题

    前言: 在本地执行date 和登录docker后的date显示的时间不一致,差一天多,不是8个小时 参考:戳这儿 先重启,查看后发现差8个小时 用里面cp localtime 再重启还是差8个小时 试 ...

  9. IE9样式错乱,IE11无法正常加载v-loading等问题 引入了babel-polyfill插件,依然出现”polyfill-eventsource added missing EventSource to window”的奇怪问题&lpar;ie所有版本都有出现&rpar;

    第一步:安装babel-ployfill (已安装请跳过此步骤) yarn add babel-ployfill 修改webpack打包配置文件:webpack.bash.conf.js // 引入b ...

  10. openstack-KVM-存储配置

    一.块存储设备 1.存储设备类型 IDE SCSI 软盘 U盘 virtio磁盘(KVM使用类型) 2.查看存储设备 lspci | grep IDE lspci | grep SCSI lspci ...