应该如何在 Ant Design Upload 组件中设置 customRequest 以使用 XMLHttpRequest?

2024-04-29

我的组件一团糟。现在我传递了一个函数,我已经尝试了一百万件事但无法让它工作。

export default class DatafileUpload extends Component {
  initialState = {
    fileUploading: false,
    fileList: [],
    status: 'empty', // 'empty' | 'active' | 'success' | 'exception'
    file: {}
  }

  state = this.initialState

  static propTypes = {
    userId: PropTypes.string.isRequired,
    datasetId: PropTypes.string.isRequired
  }

  scrubFilename = (filename) => filename.replace(/[^\w\d_\-.]+/ig, '')

  requestSignedS3Url = (file) => {
    const filename = this.scrubFilename(file.name)
    const params = {
      userId: this.props.userId,
      contentType: file.type,
      Key: `${filename}`
    };
    return api.get('/s3/signUpload', { params })
      .then(response => {
        return response.data;
      })
      .catch(error => {
        console.error(error);
      });
  }

  uploadFile = (file) => {
    this.requestSignedS3Url(file)
      .then(signResult => this.uploadToS3(file, signResult))
      .catch(error => console.log(error))
  }

  createCORSRequest = (method, url, opts) => {
    opts = opts || {};
    let xhr = new XMLHttpRequest();
    if (xhr.withCredentials != null) {
      xhr.open(method, url, true);
      if (opts.withCredentials != null) {
        xhr.withCredentials = opts.withCredentials;
      }
    } else if (typeof XDomainRequest !== "undefined") {
      xhr = new XDomainRequest();
      xhr.open(method, url);
    } else {
      xhr = null;
    }
    return xhr;
  };

  stepFunctions = () => {
    return {
      preprocess: (file) => {
        console.log('Pre-process: ' + file.name);
      },
      onProgress: (percent, message, file) => {
        this.setState({ fileUploading: true })
        console.log('Upload progress: ' + percent + '% ' + message);
      },
      onFinish: (signResult) => {
        this.setState({ fileUploading: false })
        console.log("Upload finished: " + signResult.publicUrl)
      },
      onError: (message) => {
        this.setState({ fileUploading: false })
        console.log("Upload error: " + message);
      },
      scrubFilename: (filename) => {
        return filename.replace(/[^\w\d_\-\.]+/ig, '');
      },
      onFinishS3Put: (signResult, file) => {
        console.log(signResult)
        return console.log('base.onFinishS3Put()', signResult.publicUrl);
      }
    }
  }

  uploadToS3 = async (file, signResult) => {
    const xhr = await this.createCORSRequest('PUT', signResult.signedUrl);
    const functions = this.stepFunctions()
    functions.preprocess(file)
    if (!xhr) {
      functions.onError('CORS not supported', file);
    } else {
      xhr.onload = () => {
        if (xhr.status === 200) {
          functions.onProgress(100, 'Upload completed', file);
          return functions.onFinishS3Put('potatopotato', file);
        } else {
          return functions.onError('Upload error: ' + xhr.status, file);
        }
      };
      xhr.onerror = () => {
        return functions.onError('XHR error', file);
      };
      xhr.upload.onprogress = (e) => {
        let percentLoaded;
        if (e.lengthComputable) {
          percentLoaded = Math.round((e.loaded / e.total) * 100);
          return functions.onProgress(percentLoaded, percentLoaded === 100 ? 'Finalizing' : 'Uploading', file);
        }
      };
    }
    xhr.setRequestHeader('Content-Type', file.type);
    if (signResult.headers) {
      const signResultHeaders = signResult.headers
      Object.keys(signResultHeaders).forEach(key => {
        const val = signResultHeaders[key];
        xhr.setRequestHeader(key, val);
      })
    }
    xhr.setRequestHeader('x-amz-acl', 'public-read');
    this.httprequest = xhr;
    return xhr.send(file);
  };

  handleChange = ({ file, fileList }) => {
    const functions = this.stepFunctions()
    functions.preprocess(file)
    if (!file) {
      functions.onError('CORS not supported', file);
    } else {
      file.onload = () => {
        if (file.status === 200) {
          functions.onProgress(100, 'Upload completed', file);
          return functions.onFinishS3Put('potatopotato', file);
        } else {
          return functions.onError('Upload error: ' + file.status, file);
        }
      };
      file.onerror = () => {
        return functions.onError('XHR error', file);
      };
      file.upload.onprogress = (e) => {
        let percentLoaded;
        if (e.lengthComputable) {
          percentLoaded = Math.round((e.loaded / e.total) * 100);
          return functions.onProgress(percentLoaded, percentLoaded === 100 ? 'Finalizing' : 'Uploading', file);
        }
      };
    }
    console.log('File: ', file)
    // always setState
    this.setState({ fileList });
  }

  render() {
    const props = {
      onChange: this.handleChange,
      multiple: true,
      name: "uploadFile",
      defaultFileList: this.initialState.fileList,
      data: this.uploadFile,
      listType: "text",
      customRequest: ????,
      showUploadList: {
        showPreviewIcon: true,
        showRemoveIcon: true
      },
      onProgress: ( {percent} ) => {
        this.setState({ fileUploading: true })
        console.log('Upload progress: ' + percent + '% ' );
      },
      onError: (error, body) => {
        this.setState({ fileUploading: false })
        console.log("Upload error: " + error);
      },
      onSuccess: (body)=> {
        console.log(body)
        return console.log('base.onFinishS3Put()');
      }
    };

    return (
      <Upload {...props} fileList={this.state.fileList}>
        <Button>
          <Icon type="upload" /> Upload
        </Button>
      </Upload>
    )
  }
}

我知道这段代码一团糟,没有意义,并且到处都有重复的数据。我希望它能够正常工作,然后进行清理/优化。基本上我无法使组件进度条更新,也无法使用onChange也不当我尝试使用customRequest。什么时候customRequest叫?This https://github.com/react-component/upload#customrequest解释不是很丰富...我不明白它是如何做到Ajax上传的替换的。


我也曾为此苦苦挣扎,然后我发现了你的问题。

所以我发现使用 customRequest 和 onChange 的方法是:

    <Upload name="file" customRequest={this.customRequest} onChange={this.onChange}>
      <Button>
        <Icon type="upload" /> Click to Upload
      </Button>
    </Upload>

  ...


  onChange = (info) => {
    const reader = new FileReader();
    reader.onloadend = (obj) => {
      this.imageDataAsURL = obj.srcElement.result;
    };
    reader.readAsDataURL(info.file.originFileObj);

    ...
  };

  ...

  customRequest = ({ onSuccess, onError, file }) => {
    const checkInfo = () => {
      setTimeout(() => {
        if (!this.imageDataAsURL) {
          checkInfo();
        } else {
          this.uploadFile(file)
            .then(() => {
              onSuccess(null, file);
            })
            .catch(() => {
              // call onError();
            });
        }
      }, 100);
    };

    checkInfo();
  };

可能有更好的方法来做到这一点,但我希望对您有所帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

应该如何在 Ant Design Upload 组件中设置 customRequest 以使用 XMLHttpRequest? 的相关文章

随机推荐

  • 如何将expo sdk升级到特定版本

    我想按照文档中的建议逐步升级我的expo sdk版本 这些是说明 更新到最新版本的 Expo CLI npm i g expo cli 电子邮件受保护 cdn cgi l email protection或更大的要求 如果您使用 EAS C
  • 如何在 python 中的不同终端窗口中运行函数/线程?

    我有一个这样的程序 from threading import Thread def foo1 arg print foo1 gt gt gt Something input foo1 gt gt gt Enter Something de
  • 存储库和数据映射器模式

    在大量阅读有关存储库和数据映射器的内容后 我决定在测试项目中实现这些模式 由于我对这些不熟悉 我想了解您对我如何在一个简单的项目中实现这些的看法 杰里米 米勒 说 做一些不平凡的个人编码项目 您可以在其中自由地尝试设计模式 但我不知道我做的
  • 根据自定义适配器中的条件更改特定行的背景

    我试图根据从远程服务器上的数据库收到的标志来更改行的背景颜色 在我的代码中 我创建了一个名为 disable 的 ArrayList 其中包含所有已标记的位置 我想将禁用列表中的内容与我的 ListView 中的位置相匹配 我研究了几篇帖子
  • 在 IntelliJ 插件中创建后台任务

    我正在开发一个 IntelliJ idea 插件 并希望在后台任务中运行代码 在后台任务对话框和 UI 之外的另一个线程中可见 我发现了以下内容助手类 https github com inmite android selector cha
  • 如何解决错误“AttributeError:‘SparkSession’对象没有属性‘序列化器’?

    我正在使用 pyspark 数据框 我有一些代码试图在其中转换dataframe to an rdd 但我收到以下错误 AttributeError SparkSession 对象没有属性 序列化器 可能是什么问题 training tes
  • Python - 套接字错误,地址正在使用

    我目前正在尝试在 Xubuntu 12 10 x64 上设置 SiriServer 这不是重点 当我运行服务器时 python 返回错误 socket error Errno 98 Address already in use 默认情况下
  • 对嵌套的 observable 进行排序

    我这里有一个 JSON 文件 如下所示 question What is your age range options 10 20 20 30 30 40 40 50 question How did you find us options
  • TFS 2017 - 构建服务器不构建 Visual Studio 2017

    上周在我的构建服务器上升级 Visual Studio 2017 后 MS Build 15 0 不再使用 因此 每当我尝试编译使用新功能的 Visual Studio 2017 项目时 它们都会失败 构建日志中的警告是 找不到 Visua
  • 使用 jQuery 删除 元素?

    我不想使用 style css 中的样式 因此我决定从 DOM 中删除 style css 这在 Firefox 和 IE8 中工作正常 但在 IE6 中不行 LINK href http www example com style css
  • 分配字节数组时出现奇怪的错误

    byte frame to send new byte 6 code frame to send 0x68 0x04 0x83 0x00 0x00 0x00 Array edit Error 无效的表达式术语 预期的 您只能在构造时初始化时
  • Git GUI 推送到特定分支

    我如何使用 GIT gui 推送到远程的特定分支 我似乎找不到它的选择 假设我想推送到特定的分支名称 branchOne 怎么可能呢 我正在推动 gitlab 每当您将某些内容推送到远程服务器时 您都在推送特定的分支 在您的情况下 您有一个
  • 如何使用 Python 的 __import__ 函数执行相当于“从模块导入 *”的操作?

    给定一个带有模块名称的字符串 如何导入模块中的所有内容 就好像您调用了 from module import 即给定字符串 S module 如何获得与以下内容等效的内容 import S fromlist 这似乎没有按预期执行 因为它没有
  • 从浏览器使用 node.js 的文件系统功能

    我想创建一个从服务器中删除文件的函数 我打算使用此功能将设置 即数据库文件 恢复到默认状态 我使用以下命令运行我的服务器 node server js 我知道node js的文件系统 https nodejs org api fs html
  • 在类 Illuminate\Support\Facades\Schema 中找不到方法“create”

    我使用的是 Laravel 5 3 在 PhpStorm 中 create 方法和许多其他方法下有错误 我尝试了所有 ide helpers 但没有解决问题 有没有办法解决这个问题和自动完成 我发现问题的答案在于使用行 use Illumi
  • Eclipse Faces 配置编辑器不工作

    Summary 编辑 faces config xml 时 Eclipse 中的 Faces 配置编辑器不会打开 这是一个 JavaServer Faces 项目 Details 日食3 7 2 Eclipse m2e 1 0 1 m2e
  • 从哈希表中删除一个值的成本是多少?

    现在我有一个问题 当我们在插入过程中使用线性探测时 有人问我从哈希表中删除值的成本 通过阅读互联网上的各种内容 我发现它必须与负载因子有关 虽然我不确定 但我读到了负载因数与所需探头数量之间的关系 探头数量 1 1 LF 所以我相信成本必须
  • 特殊字符无法正确显示

    In a TextArea 我正在使用 字符 但无法正确显示 相反 它显示的是这样的 我如何获得 字符才能正常显示 您可能没有使用 Ascii 撇号 而是使用一些非 Ascii 标点符号 例如正确的标点撇号 出现问题的原因是您的 HTML
  • Java中printf左对齐

    当我运行该程序时 阶乘值右对齐 有没有办法让它左对齐 同时保持中间 50 个空格 public class Exercise 5 13 public static void main String args int numbers 1 2
  • 应该如何在 Ant Design Upload 组件中设置 customRequest 以使用 XMLHttpRequest?

    我的组件一团糟 现在我传递了一个函数 我已经尝试了一百万件事但无法让它工作 export default class DatafileUpload extends Component initialState fileUploading f