vue之axios上传文件图片

<template>
  <div class="upload-area-wrap">

    <div class="upload-area">
      <p class="tip-title">上传文件 - file upload</p>

      <div class="upload-detail-wrap">
        <div class="upload-detail">
          <div class="progressbar" v-show="showProgressBar">
            <div :class="[fill?'fill':'clearfill']" :style="{width:widthcount+'%'}">{{proscount}}</div>
            <img class="d-pictures" :src="picUrl" width="30" height="30" alt="缩略图">
            <span class="dictionary-name">{{textName}}</span>
            <span class="dictionary-name">{{textSize}}</span>
            <span class="dictionary-name">{{textformat}}</span>
            <i class="delete-d">删除</i>
          </div>
        </div>

      </div>

      <form class="uoload-wrap btn-primary file-uploads" enctype="multipart/form-data" >

        <i>+</i>select
        <label class="file" for="file"></label>
        <!--<input class="file" name="file" type="file" :acceptUrl = "acceptUrl"  @change="uploadFile($event)"/>-->
        <input class="file" name="file" type="file" @change="uploadFile($event)"/>
      </form>

    </div>




  </div>

</template>
<script>
  import * as baseUrl from '../../../assets/common/url/url.js'
  export default {
    name:'fileUpload',
    // proops:{
    //   acceptUrl:{
    //     type:String,
    //     default:''
    //   }
    // },
    data(){
      return {
        formData:'',
        name:'',
        file:[],
        acceptUrl:'',
        proscount:'',
        fill:'',
        clearfill:'clearfill',
        timer:'',//进度条定时器
        fileData:'',
        showProgressBar:false,
        textName:'',
        textSize:'',
        textformat:'',
        picUrl:'',
        widthcount:'',
      }
    },
    name:'SelectTheFile',
    created(){
    },
    methods:{

      // 获取文件
      uploadFile($event){
        this.fill = false;
        this.showProgressBar = true;
        this.formData = new FormData();
        for (let i = 0; i < $event.target.files.length; i++) {
          this.formData.append('file', $event.target.files[i]);
          this.file.push($event.target.files[i]);
        }
        //文件字节大小
        console.log($event);
        let Osize = this.conver(this.formData.get('file').size);
        //文件类型
        let subIndex =(this.formData.get('file').type).lastIndexOf('/')+1;
        let Oformat = this.formData.get('file').type;
        let data = this.formData.get('file');
        this.textName = data.name;
        this.textSize = this.formatFileSize(data.size);
        this.textformat = Oformat.substring(Oformat.lastIndexOf('/')+1,Oformat.length);
        //this.textformat = Oformat.split("\/")[1];
        console.log(this.formData.get('file'));
        // console.log($event.target.files);
        this.submit(this.formData);
        //进度条
        // this.timeBar();
        $event.target.value = '';
      },
      //进度条时间
      timeBar(){
        var self = this;
        self.fill != self.fill ;
        self.proscount = 0;
        self.timer = setInterval(()=>{
          self.proscount ++;
          // console.log(this.proscount)
          self.fill = true;
          if( self.proscount == 100){
            clearInterval(self.timer);
          }
        },10);

      },
      //选择文档类型判断
      checkFileType: function (fileType) {
        const acceptTypes = ['xls', 'doc', 'jpg'];
        for (var i = 0; i < acceptTypes.length; i++) {
          if (fileType === acceptTypes[i]) {
            return true;
          }
        }
        return false;
      },
      formatFileSize: function (fileSize, idx) {
        var units = ["B", "KB", "MB", "GB"];
        idx = idx || 0;
        if (fileSize < 1024 || idx === units.length - 1) {
          return fileSize.toFixed(1) +
            units[idx];
        }
        return this.formatFileSize(fileSize / 1024, ++idx);
      },
      //获取文件大小
      conver(limit){
        let size = '';
        if(limit < 0.1*1024){
          size = limit.toFixed(2)+'B'
        }else if(limit < 0.1*1024*1024){
          size = (limit/1024).toFixed(2)+'KB'
        }else if(limit< 0.1*1024*1024*1024){
          size = (limit/(1024*1024)).toFixed(2)+'MB'
        }else{
          size = (limit/(1024*1024*1024)).toFixed(2)+'G'
        }
        return size;
      },
      // 发送文件
      submit(data) {
        var that = this;
        that.$ajax({
          url:`${baseUrl.upload}`,
          method:'post',
          data:data,
          header:{
            // "Access-Control-Allow-Origin":"http://192.168.20.191:9091",
            'Content-Type': 'multipart/form-data',
          },
          onUploadProgress:progressEvent=> {//原生获取上传进度的事件
            if (progressEvent.lengthComputable) {
              // this.proscount = 0;
              this.fill != this.fill ;
              var complete = (progressEvent.loaded / progressEvent.total * 100 | 0) ;
              this.proscount = complete + '%';
              this.fill = true ;
              this.widthcount = complete;
            }
          }
        }).then(res=>{
          console.log(res);
          if(res.data.code == '0000'){
            // alert('上传成功');
            this.picUrl = res.data.data;
          }else{
            alert('上传失败')
          }
        }).catch(err =>{

          console.log(err);
          clearInterval(this.timer);

          alert('上传失败');
        });


      },

      onUploadProgressSuccess:function(){

      }
    }
  }
</script>
<style>
  .upload-area-wrap{
    position: relative;
    width: 580px;
    height: 310px;
    margin: 30px auto;

  }
  .uoload-wrap{
    display: inline-block;
    font-weight: 400;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    border: 1px solid transparent;
    padding: .5rem .75rem;
    font-size: 1rem;
    line-height: 1.25;
    border-radius: .25rem;
    transition: all .15s ease-in-out;
  }
  .d-pictures{
    float: left;
  }
  .dictionary-name{
    display: inline-block;
    height: 30px;
    line-height: 30px;
    float: left;
    margin-left: 15px;
  }
  .upload-area{
    width: 100%;
    min-height: 300px;
    border: 1px solid #8c939d;
    border-radius: 10px;
    background: #fff;
  }
  .upload-detail{
    width: 100%;
    height: 230px;
    box-sizing: border-box;
    padding: 10px 10px;
  }
  .delete-d{
    display: inline-block;
    color: #ff5e48;
    float: right;
    height: 30px;
    line-height: 30px;
    margin-right: 20px;
  }
  .tip-title{

    margin:5px 10px;
    width: auto;
  }
  .btn-primary{
    color: #fff;
    background-color: rgb(165, 232, 141);
    border-color: green;
    float: right;
    margin-right: 20px;
  }
  .file-uploads{
    overflow: hidden;
    position: relative;
    text-align: center;
    display: inline-block;
  }
  label{
    background: #fff;
    opacity: 0;
    font-size: 20em;
    z-index: 1;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
    width: 100%;
    height: 100%;
  }
  input[type = file]{
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
  }
  .progressbar{
    position: absolute;
    width:calc(100% - 20px);
    height:50px;
  }
    .fill{
    /*animation:move 2s;*/
    text-align: center;
    background: rgb(172, 242, 129);
    border-radius: 32px;
  }
  .clearfill{
    background: none;
    width: 0;
  }
  @keyframes move{
    0%{
      width: 0;
    }
    100%{
      width: 100%;
    }

  }
</style>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue中使用axios上传图片,你可以按照以下步骤进行操作: 1. 首先,确保你已经安装了axiosvue-axios插件。如果没有安装,可以通过以下命令进行安装: ``` npm install axios vue-axios ``` 2. 在你的Vue组件中,导入axiosvue-axios,并将vue-axios插件注册到Vue实例中。例如: ```javascript import axios from 'axios' import VueAxios from 'vue-axios' export default { // ... created() { Vue.use(VueAxios, axios) }, // ... } ``` 3. 在你的Vue组件中,创建一个方法来处理上传图片的逻辑。例如: ```javascript methods: { handleFileUpload(event) { const file = event.target.files[0] const formData = new FormData() formData.append('image', file) axios.post('/upload', formData) .then(response => { // 处理上传成功后的逻辑 }) .catch(error => { // 处理上传失败后的逻辑 }) } } ``` 在上述代码中,我们首先从事件对象中获取要上传的文件。然后,我们创建一个FormData对象,并将文件附加到FormData中。接下来,我们使用axios的post方法发送POST请求到服务器的`/upload`端点,将FormData作为请求体发送。根据服务器的实现,你可能需要调整请求URL和请求体中的参数名。 4. 在你的Vue模板中,添加一个文件选择输入框,并绑定`change`事件到上面创建的方法。例如: ```html <input type="file" @change="handleFileUpload"> ``` 这样,当用户选择文件后,`handleFileUpload`方法将被调用,并且文件将被上传到服务器。 请注意,上述代码仅涉及前端部分的文件上传逻辑,你还需要在服务器端实现相应的上传处理逻辑。具体的实现方式取决于你使用的后端技术栈,例如Node.js、Django、Spring等。 希望这能帮助到你!如果有任何问题,请随时追问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值