点击/拖拽两种方式,预览并上传png/jpg/jpeg格式图片

该博客介绍了如何通过点击和拖拽两种方式预览并上传PNG、JPG及JPEG格式的图片。同时,提到了在拖拽时存在文件名显示的bug,有待进一步修复。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
  <div class="content">
    <div class="PictureBox">
        <img class="Picture"   alt="请将图片拖拽到此处或点击选择文件"/>
    </div>
    <!-- 按钮 -->
    <div  style="margin-top: 20px;" class="Button">
      <input  type="file" @change="selectPicture($event)" ref="img" />
      <!-- <span class="imgName" style="font-size: 5px">未选择图片</span> -->
      <button  @click="upload" >上传</button>
    </div>

  </div>

</template>
<script>
  import axios from 'axios'
  export default {
    data () {
      return {
        imgUrl: '',
      }
    },
    mounted() {
      let upload = document.querySelector('.Picture');
      upload.addEventListener('dragenter', this.onDrag, false);
      upload.addEventListener('dragover', this.onDrag, false);
      upload.addEventListener('drop', this.onDrop, false);
    },
    methods: {
      onDrag (e) {
        e.stopPropagation();
        e.preventDefault();
      },
      onDrop (e) {
        e.stopPropagation();
        e.preventDefault();
        console.log("dddd")
        this.imgPreview(e.dataTransfer.files);
        // this.uploadFile(e.dataTransfer.files);
      },
      //图片预览
      imgPreview (files) {
        console.log("cccc")
        let read = new FileReader();
        let imgUrl = document.querySelector('.Picture');
        read.readAsDataURL(files[0]);
        read.onload = function () {
          document.querySelector('.Picture').src = this.result;
        }
      },
      // 点击按钮选择图片
      selectPicture(e) {
        let imgfile = this.$refs.img;
        let reader = new FileReader();
        reader.readAsDataURL(imgfile.files[0]);
        // document.querySelector('.imgName').innerHTML = imgfile.files[0].name;
        reader.onload = function() {
        document.querySelector('.Picture').src = this.result;
        };
      },
      //图片上传
      upload (files) {
        let params = new FormData();
        params.append('file', files[0]);
        axios.post('http://localhost:3000/upload', params);
      }
    },
  }


</script>
<style>
  .content{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .PictureBox {
    display: flex;
    width: 400px;
    height: 200px;
    border: 1px solid ;
    justify-content: center;
    align-items: center;
    /* background-color: #00FFFF; */
  }
  .Picture{
    display: flex;
    width: 90%;
    height: 90%;

    border: 2px dashed #f00;
    /* background-color: #00FF00; */
  }

</style>

 

备注:拖拽时文件名有bug,有空完善

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值