h5图片上传功能( <input type=\"file\" @change=\"remarkPicture($event)\" accept=\"image/*\">)

故事扮演 提交于 2019-11-27 02:37:39

最近在写车辆管理的H5页面,遇到图片上传功能,发现移动端没有合适的框架实现上传图片。  我们都知道,html5中有个input type=file元素。用该元素可以实现页面上传文件的功能!!!

现在我们来研究一下:

首页静态页面 

html:

 <div class="remark">
      <span style="display: block;">备注照片:</span>

      <div class="upImg">
        <img :src="remarkimg" alt="" class="upload">
        <img src="@/assets/shut.png" alt="" class="del" @click="delRemark" v-show="remarkimg != ''">
      </div>

      <div class="upload_box" v-show="remarkimg == ''">
        <img src="@/assets/upload.png" alt="">
        <input type="file" @change="remarkPicture($event)" accept="image/*">
      </div>
    </div>



css样式:

 .remark {
      padding: 30px 30px 30px 0;
      font-size: 32px;
      margin-left: 30px;
      border-bottom: 2px solid #ccc;
      font-weight: 600;
      textarea {
        display: block;
        margin: 20px 0 0 80px;
        width: 610px;
      }
      .upImg {
        display: inline-block;
        position: relative;
        .upload {
          width: 152px;
          height: 152px;
          margin-top: 20px
        }
        .del {
          width: 40px;
          height: 40px;
          position: absolute;
          top: 0px;
          right: -20px;
          z-index: 999;
        }
      }
      .imgLis {
        display: inline-block;
      }
      #upload {
        width: 152px;
        height: 152px;
        margin-top: 20px
      }
      .upload_box{
        // margin-top: 20px;
        display: inline-block;
        vertical-align: top;
        position: relative;
        img {
          width: 152px;
          height: 152px;
          margin-top: 20px
        }
        input {
          position: absolute;
          top: 0;
          left: 0;
          opacity: 0;
          width: 152px;
          height: 152px;
        }
      }

点击+  选择图片触发@change="remarkPicture($event)"事件 

console.log(e.target.files[0])打印出的值

 

应后台接口需要 参数 service  file  userId :如图

所以我把需要的参数通过append的方法追加到formData中,然后将值传到后台,然后后台处理,获取图片链接(res.data)

 

 

前面我们说到了formData  

FormData的主要用途有两个:

1、将form表单元素的name与value进行组合,实现表单数据的序列化,从而减少表单元素的拼接,提高工作效率。
2、异步上传文件

 我们主要使用的是:

//通过FormData构造函数创建一个空对象
var formdata=new FormData();
//可以通过append()方法来追加数据
formdata.append("name","laotie");

图片上传后的页面:

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!