前端通过input标签封装Upload组件实现文件上传

852 阅读1分钟

前端通过input标签实现文件上传

基于input标签封装upload组件

import React, { Component, Fragment, createRef } from 'react';
import './Upload.less';

type StateType = {
  [propName: string]: any;
};

interface changeFileType {
  (e: any): any;
}

type PropType = {
  accept: string; // 父级传过来的文件接收类型
  changeFile: changeFileType; // 父级传过来的文件修改事件函数
  [propName: string]: any;
};

interface Upload {
  state: StateType;
  props: PropType;
  inputDom: any;
}

class Upload extends Component {

  constructor(props: any) {
    super(props);
    this.state = {
    };
    this.inputDom = createRef(); // input标签DOM
  }
  
  // 文件修改的事件函数
  private changeFile = (e: any): void => {
    const file = e.target.files[0];
    if (!file.size) {
      return;
    }
    const formData = new FormData();
    formData.append('file', file);
    const params = {
      file: formData,
      fileType: file.type
    };
    this.props.changeFile(params);
    this.inputDom.current.value = null;
  }

  render() {
    const { accept } = this.props;

    return (
      <Fragment>
        <input type="file" ref={this.inputDom} id="file" accept={accept} onChange={this.changeFile} className="file-input" />
      </Fragment>
    )
  }
}

export default Upload;

修改样式

修改样式,使得Upload组件基于父级绝对定位,并且宽高等于父级,层级在最上方,不透明度为0

.file-input {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}

请求头添加’Content-Type’:‘multipart/form-data’

请求头需要添加'Content-Type':'multipart/form-data'
在这里插入图片描述

父级使用封装好的Upload组件上传文件

// 图片文件上传
private changeImgFile = (e: any): void => {
  this.setState({
    imgFile: e.file,
  });
}
  
<Upload accept='image/*' changeFile={this.changeImgFile} />

常见的input标签accept属性接收的参数

值描述描述
audio/*接受所有的声音文件
video/*接受所有的视频文件
image/*接受所有的图像文件
audio/ ,video/ ,image/*接受所有的声音、视频、图像文件
*接受所有文件
MIME_type一个有效的 MIME 类型,不带参数。请参阅 IANA MIME 类型,获得标准 MIME 类型的完整列表