input元素type改为file类型, accept限制指定的文件类型,multiple可以多传送文件

<input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" @getFile="update($event)"/>

FormData私有类对象,访问不到,可以通过get判断值是否传进去

export default {
    data() {
      return {
        formData: '',
        name: '',
        file: []
      }
    },
    name: 'SelectTheFile',
    methods: {
      // 关闭框
      cancel: function() {
        this.$emit('info', false);
      },
      // 获取文件
      getFile: function(event) {
        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(this.formData.get('file'));
      },
      // 发送文件
      submit: function(event) {
        event.preventDefault();
        // 创建form对象
        // 通过append向form对象添加数据
        this.formData.append('name', this.name);
        server.uploadingFile(this.formData).then(response => {
          console.log(response.data);
        }).catch(err => {
          console.log(err);
        })
      }
    }
  }
import axios from 'axios';
import baseUrl from '../config';

export default function(url, {
  method = 'post',
  timeout = 10000,
  data = {},
  headers = {'Content-Type': 'application/json;charset=UTF-8;'},
  dataType = 'json'
}) {
  const config = {
    method: method,
    timeout: timeout,
    url: url,
    baseURL: baseUrl.URL_CNODEJS,
    data: data,
    headers: headers,
    dataType: dataType
  };
  return axios(config);
}

 

import axios from '../services/axios';
const server = {
  uploadingFile(data) {
    return axios('/goupload', {
      method: 'post',
      data: data,
       // 修改请求头才能传文件
      headers: {'Content-Type': 'multipart/form-data'}
    })
  }
};

export default server;

改变input默认样式

    outline: none;
    background-color: transparent;
    filter: alpha(opacity=0);
    opacity: 0;

 

Logo

前往低代码交流专区

更多推荐