antd在form中使用上传组件

  1. form表单中的enctype设置为multipart/form-data
    enctypeencodetype规定了form表单在发送到服务器时候编码方式。
    enctype的值:
  • application/x-www-form-urlencoded:(默认)在发送前编码所有字符,但是在用文本的传输和MP3等大型文件的时候,使用这种编码就显得 效率低下。不能用于其他文件上传。
  • multipart/form-data:不对字符编码。当表单数据有多部分构成,既有文本数据,又有文件等内容,将文件以二进制的形式上传,这样可以实现多种类型的文件上传。只有使用了,才能完整的传递文件数据。
  • text/plain:纯文体的传输。空格转换为 "+" 加号,但不对特殊字符编码。
  1. 包含上传组件的表单常常是希望表单中的内容能和表单中的内容一起提交,但是antd的上传组件会自动上传,这不符合我们的预期,这里我们采用的方法是
  • Upload组件中定义beforeUpload方法并且返回false拦截文件的自动上传,同时把文件信息添加到state
  • 我目前的需求是只允许上传一个文件,需要在onChange方法中按照文档中给的方法,将上传列表的长度始终设为1;如果你不限制上传文件的个数,那么你需要在这里添加onRemove方法用于在删除列表时候实时更新state
  • 其他内容通过getFieldsValue获得即可,上传的文件可以直接在state
...
class SelectModal extends PureComponent {
  ...
  submitForm = (e) => {
    e.preventDefault();
    const {
      form: { getFieldsValue },
      actions: { postUniverse },
     ...
    } = this.props;
    const formData = getFieldsValue();
    postUniverse({ ...formData, file: this.state.fileList });
  };
  
  handleUploadChange = (info) => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map((file) => {
      const res = { ...file };
      if (file.response) {
        res.url = file.response.url;
      }
      return res;
    });
    this.setState({ fileList });
  };

  // 拦截文件上传
  beforeUploadHandle = (file) => {
    this.setState({ fileList: [file] });
    return false;
  };

  upLoadProp = () => ({
    action: '',
    accept: '.xlsx,.csv',
    listType: 'text',
    onChange: this.handleUploadChange,
    beforeUpload: this.beforeUploadHandle,
  });

  render() {
    ...
    return (
        
... ...
); } } ...

此时提交的表单中file为文件:
文件内容在这里

antd在form中使用上传组件_第1张图片
image.png

image.png

你可能感兴趣的:(antd在form中使用上传组件)