Ant Design Upload 获取文件内容

新手上路,请多包涵

我正在使用 Ant Design 上传组件。有没有一种方法可以将所选文件的内容作为 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>

原文由 hoan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
2 个回答

深受 Shreyans 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>;

原文由 hoan 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

原文由 Shreyans Shrivastav 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题