from 表单上传图片

2019-05-30  本文已影响0人  Ordenme

一、基础表单上传图片


上传input样式重置,可自定义。

<input type="file"  id="fileBtn" style="display: none;" />y

from 表单中必须添加该属性 enctype="multipart/form-data",否则发送不出选择的数据

<style>
.btn .btn-primary .upload-picture-btn{
   上传按钮样式自定义.....
   input type ='file'标签 需display:none
}
</style>
/*=========================*/
<form id="settings-avatar-form" 
      method="post" 
      action=""
      enctype="multipart/form-data"> //该属性必加
   <div class="form-group">
      <b>当前头像</b>
        <img id='img' src="/Public/web/images//avatar.png">
   </div>
   <div class="form-group">
      <p class="help-block">
          你可以上传JPG、GIF或PNG格式的文件,文件大小不能超过<strong>2M</strong>。
      </p>
    <div class="form-group">
      <a href="javascript:void(0)" class="upImg">
          <label id="upload-picture-btn"  class="btn btn-primary upload-picture-btn" for="fileBtn">
              上传新头像
            <input type="file"  id="fileBtn" style="display: none;" />
          </label>
      </a>
      <a href="javascript:void(0)" class="upImgs" style="display: none">
          <button type="submit"
                  form="settings-avatar-form" //表单中提交按钮需要 设置from的id 可直接发送提交
                  class="btn btn-primary upload-picture-btn">保存
          </button>
          <label id="upload-picture-btns"
                for="fileBtn">
                    重新选择
            <input type="file"  id="fileBtns" style="display: none;" />
          </label>
        </a>
</form>


<script type="text/javascript">
     // 控制上传图片方法
    function  headImg (that) {
      $('#img').css({width:'270px',height:'270px'}) //控制上传头像大小
      $('#upload-picture-btns').css({color:'#666666',marginLeft:'10px'})
      let filePath = $(that).val();
      let fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
      // 生成浏览器上预览本地图片或者视频的路径
      let src = window.URL.createObjectURL(that.files[0]);
      // 检查是否是图片
      if(!fileFormat.match(/.png|.jpg|.jpeg/)) {
        alert('上传错误,文件格式必须为:png/jpg/jpeg');
        return;
      }else{
        $('.upImg').css('display','none');
        $('.upImgs').css('display','block');
        $('#img').attr('src',src);  img标签设定本地图片地址
      }
    };
    $('#fileBtn').change(function () {
      headImg(this)
    });
    $('#fileBtns').change(function () {
      headImg(this)
    });
  </script>

读取用户选择本地文件的内容,可使HTML5中添加的DOM的File API

const inputFiles = document.getElementById('input').files;  // 打印出FileList对象,并有length

FileList对象(inputFiles[0])提供的三个属性包含有关该文件的有用信息。
name:该文件的名称为只读字符串。这只是文件名,不包含任何路径信息。
size :文件大小(以字节为单位)作为只读64位整数。
type:将文件的MIME类型作为只读字符串或""无法确定类型
其他属性
lastModified: 1159190361027
lastModifiedDate: Thu May 30 2019 12:21:01 GMT+0800 (中国标准时间) {}
webkitRelativePath: ""

window.URL.createObjectURL()

上一篇 下一篇

猜你喜欢

热点阅读