vue移动端图片上传

没有用插件就简单的图片上传

页面布局如下

<div class="input-up">
          <input
            type="file"
            accept="image/*"
            style="display:none"
            @change="changeImg()"
            name="upload_file"
            ref="input"
          />
          <div class="uploads" v-if="otherimg!=''" @click="upload">
            <img :src="otherimg" alt />
          </div>
          <div class="upload" v-else @click="upload">
            <span>+</span>
            <p>添加名片或相关图片</p>
          </div>
 </div>

css样式

.input-up {
  padding: 0.26rem 0.18rem;
}
.input-up .upload {
  width: 2.36rem;
  height: 1.4rem;
  border: 1px solid #f5f5f5;
}
.input-up .upload span {
  display: block;
  text-align: center;
  font-size: 0.6rem;
  color: #d8d8d8;
}
.input-up .uploads {
  width: 1.4rem;
  height: 1.4rem;
  border: 1px solid #f5f5f5;
}
.input-up .uploads img {
  display: block;
  width: 100%;
  height: 1.4rem;
}
.input-up .upload p {
  text-align: center;
  font-size: 0.2rem;
  color: #d8d8d8;
}

接口请求用的是axios

<script>
import { Toast } from 'mint-ui'  // mint-ui的弹窗提示
export default {
data () {
    return {
       customer_id:"",
       otherimg:"",
       imgData: [] // 选择图片保存数组
    }
},
methods: {
   //图片change事件
   changeImg () {
      // 上传图片事件
      var files = this.$refs.input.files
      var that = this
      function readAndPreview (file) {
        if (file !== undefined) {
          if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
            var reader = new FileReader()
            reader.onload = function (e) {
              // 避免重复上传同个图片
              if (that.imgData.indexOf(e.target.result) === -1) {
                that.imgData.push(e.target.result)
                that.otherimg = that.imgData.pop() //每次展示最后一个上传的图片
              } else {
                Toast('已有该图片')
              }
            }
            reader.readAsDataURL(file)
          }
        }
      }
      readAndPreview(files[0])
      if (files.length === 0) {
        return false
      }
      console.log(that.imgData)
      that.uploadFile(files[0])  // 文件上传服务器
    },
   // 图片上传接口
    uploadFile (file) {
      this.formData = new FormData()
      // 添加文件流
      this.formData.append('files', file, file.name) 
     //添加接口的参数 看需求传或不传
      this.formData.append('user_token', localStorage.getItem('user_token')) 
      this.formData.append('customer_id', this.customer_id)
      this.axios.post('/customerinfo/uploadImg',
       headers: {
           'Content-Type': 'multipart/form-data'
        },        
      this.formData    
      ).then(res => {
        if (res.code === 0) {
         //返回图片的地址res.data
          this.otherimg = res.data
          Toast('上传成功')
        }
      })
    },
    upload () {
      // 点击触发按钮
      this.$refs.input.dispatchEvent(new MouseEvent('click'))
    }
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。