【问题标题】:Ant Design Upload get file contentAnt Design Upload 获取文件内容
【发布时间】:2019-03-19 10:01:03
【问题描述】:

我正在使用 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>

【问题讨论】:

    标签: javascript reactjs file antd


    【解决方案1】:

    受到this 来自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>;
    

    【讨论】:

      【解决方案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

      【讨论】:

      • 这个程序只是打印文件的内容。但是我怎样才能获得内容而不是打印。
      【解决方案3】:

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

      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,我们可以显示文件的内容。 上述方法对我有用。

      【讨论】:

        猜你喜欢
        • 2018-04-24
        • 1970-01-01
        • 2022-01-22
        • 2021-02-06
        • 2023-01-20
        • 1970-01-01
        • 2021-01-31
        • 1970-01-01
        • 2021-01-10
        相关资源
        最近更新 更多