【问题标题】:React AntDesign add uploaded images to FormDataReact AntDesign 将上传的图片添加到 FormData
【发布时间】:2019-07-17 15:52:38
【问题描述】:

我想使用image uploader from AntDesign library。这是snapshot

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)

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

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

【问题讨论】:

    标签: reactjs antd


    【解决方案1】:

    antdUpload 组件正在后台为您上传。但如果你不想这样做,稍后再上传文件,你也可以在beforeUpload prop 的帮助下实现。

    From the docs:

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

    我已经写了一个例子,并在必要的地方添加了 cmets:

    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"));
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-07
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多