Ant Design Upload获取文件内容

时间:2019-03-19 10:01:04

标签: javascript reactjs file antd

我正在使用Ant Design Upload组件。有没有一种方法可以让我在JavaScript中将所选文件的内容作为字符串来显示在页面上?

理想情况下,我想访问file.data之类的东西。

<Upload
    accept=".txt, .csv"
    showUploadList={false}
    beforeUpload={(file, fileList) => {
        // Access file content here and do something with it
        console.log(file);

        // Prevent upload
        return false;
    }}
>
    <Button>
        <Icon type="upload" /> Click to Upload
    </Button>
</Upload>

3 个答案:

答案 0 :(得分:2)

const { Upload, message, Button, Icon, } = antd;

const props = {
  name: 'file',
  action: '//jsonplaceholder.typicode.com/posts/',
  headers: {
    authorization: 'authorization-text',
  },
  onChange(info) {
    if (info.file.status !== 'uploading') {
       let reader = new FileReader();
        reader.onload = (e) => {
           console.log(e.target.result);
        }
        reader.readAsText(info.file.originFileObj);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
};

ReactDOM.render(
  <Upload {...props}>
    <Button>
      <Icon type="upload" /> Click to Upload
    </Button>
  </Upload>,
  mountNode
);

请检查CodePen

答案 1 :(得分:0)

受到thisShreyans Shrivastav答案的启发,但经过修改以更好地满足要求。您可以使用FileReader来读取文件的内容:

<Upload
    accept=".txt, .csv"
    showUploadList={false}
    beforeUpload={file => {
        const reader = new FileReader();

        reader.onload = e => {
            console.log(e.target.result);
        };
        reader.readAsText(file);

        // Prevent upload
        return false;
    }}
>
    <Button>
        <Icon type="upload" /> Click to Upload
    </Button>
</Upload>;

答案 2 :(得分:0)

我有类似的要求来查看上传的文件。我遵循了以下方法。

const { Dragger } = Upload;
state = {
  document: [],
};

onChangeDragger = (event) => {
  event.fileList.forEach((list) => {
    if (list.uid === event.file.uid) {
      list.url = URL.createObjectURL(event.file);
    }
  });
  if (event.fileList.length <= 1) {
    this.setState({ document: event });
  }
};

<Form formName="sample" form={form}>
  <Form.Item name={REQUEST_MODEL.document}>
    {form.getFieldDecorator("document", { initialValue: {} })(
      <Dragger
        accept={ACCEPTABLE_FILE_TYPES.join(", ")}
        name="file"
        fileList={document.fileList}
        showUploadList={false}
        onChange={(event) => this.onChangeDragger(event)}
        multiple={false}
        disabled={document?.fileList?.length >= 1}
      >
        <p className="ant-upload-drag-icon">
          <UploadCloudIcon />
        </p>
      </Dragger>
    )}
  </Form.Item>
</Form>;

{
  document?.fileList &&
    document.fileList.map((file) => (
      <div key={file.uid} className={Styles.uploadList}>
        <div className={Styles.uploadFileName}>
          <a href={file.url} target="_blank" rel="noopener noreferrer">
            {file.name}
          </a>
        </div>
      </div>
    ));
}

该方法的想法是使用状态并将文件插入文档状态中。在 onChangeDragger 函数中,当文件插入状态时,我们需要创建 url(即使用 URL.createObjectURL(event.file))并将文件的 url 附加到状态中。通过访问 url,我们可以显示文件的内容。 上述方法对我有用。