React AntDesign 将上传的图像添加到 FormData

Gin*_*ead 7 reactjs antd

我想使用AntDesign 库中的图像上传器。这是一个快照

import { Upload, Icon, Modal } from 'antd'

class PicturesWall extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    fileList: [],
  }

  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    })
  }

  handleChange = ({ fileList }) => this.setState({ fileList })

  render() {
    const { previewVisible, previewImage, fileList } = this.state
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    )
    return (
      <div className="clearfix">
        <Upload
          action="//jsonplaceholder.typicode.com/posts/"
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList.length >= 3 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    )
  }
}

ReactDOM.render(<PicturesWall />, mountNode)
Run Code Online (Sandbox Code Playgroud)

我很难理解这里发生了什么。我可以使用const img=event.target.files[0] 之类的东西从这个组件获取图像吗 ?

我想要的只是将上传的图像放入数组并使用 FormData 将 axios.post 请求发送到后端。我是 React 的新手。如果这很明显,请原谅我。提前谢谢你

meh*_*sum 26

antdUpload组件在幕后为您上传。但是,如果您不想这样做,稍后再上传文件,您也可以借助beforeUploadprop 来实现。

从文档

beforeUpload: 上传前执行的钩子函数。上传将停止并返回 false 或被拒绝的 Promise。警告?IE9 不支持此功能

我写了一个例子并在必要时添加了评论:

class PicturesWall extends React.Component {
  state = {
    previewVisible: false,
    previewImage: "",
    fileList: []
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = file => {
    this.setState({
      previewImage: file.thumbUrl,
      previewVisible: true
    });
  };

  handleUpload = ({ fileList }) => {
    //---------------^^^^^----------------
    // this is equivalent to your "const img = event.target.files[0]"
    // here, antd is giving you an array of files, just like event.target.files
    // but the structure is a bit different that the original file
    // the original file is located at the `originFileObj` key of each of this files
    // so `event.target.files[0]` is actually fileList[0].originFileObj
    console.log('fileList', fileList);

    // you store them in state, so that you can make a http req with them later
    this.setState({ fileList });
  };

  handleSubmit = event => {
    event.preventDefault();

    let formData = new FormData();
    // add one or more of your files in FormData
    // again, the original file is located at the `originFileObj` key
    formData.append("file", this.state.fileList[0].originFileObj);

    axios
      .post("http://api.foo.com/bar", formData)
      .then(res => {
        console.log("res", res);
      })
      .catch(err => {
        console.log("err", err);
      });
  };

  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <div>
        <Upload
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleUpload}
          beforeUpload={() => false} // return false so that antd doesn't upload the picture right away
        >
          {uploadButton}
        </Upload>

        <Button onClick={this.handleSubmit} // this button click will trigger the manual upload
        >
            Submit
        </Button>

        <Modal
          visible={previewVisible}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: "100%" }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}

ReactDOM.render(<PicturesWall />, document.getElementById("container"));
Run Code Online (Sandbox Code Playgroud)

  • 知道 beforeUpload 需要返回 false,很有帮助 (4认同)