【问题标题】:How do you implement XMLHttpRequest in javascript using ant design Upload component to send to google cloud storage?如何使用 ant design Upload 组件在 javascript 中实现 XMLHttpRequest 发送到谷歌云存储?
【发布时间】:2018-02-13 06:10:37
【问题描述】:

我正在尝试使用 XML api 上传到谷歌云存储。这是用于执行此操作的示例表单。 感谢布兰登·亚伯勒

<form action="http://my-bucket.storage.googleapis.com" method="post" enctype="multipart/form-data">
   <input type="text" name="key" value="">
   <input type="hidden" name="signature" value="sample_token=">
   <input name="file" type="file">
   <input type="submit" value="Upload">
</form>

我也在使用 ant design Upload 组件来做到这一点。

https://ant.design/components/upload/

文档指示使用“customRequest”属性来实现您自己的 XMLHttpRequest。此外,它还链接到描述“customRequest”接收的对象的更多文档,我在下面将其解构为参数。

https://github.com/react-component/upload#customrequest

我已经尝试实现了。

render() {
  const props = {
    name: 'file',
    action: '//localhost:3000/my-express-endpoint',
    data: {
      'key': 'value'
    },
    customRequest({ onProgress, onError, onSuccess, data, filename, file, withCredentials, action, headers }) {
      let data = new FormData();   // Using FormData counting on browser support.
      data.append('signature', 'sample_token');

      let xhr = new XMLHttpRequest();
      xhr.open('POST', 'http://my-bucket.storage.googleapis.com', true);
      xhr.onload = function () {
        // do something to response
        console.log(this.responseText);
      };
      xhr.send(data);
    }
  };

  return (
    <div className="container">
      <Dragger {...props}>
        ...drop file here
      </Dragger>
    </div>
  )
}

我不清楚如何执行 customRequest。由于我正在覆盖,这是否会使 customRequest 道具之外的其他道具 name, action, data 无效,并且现在在 customRequest 道具中处理,因为它们是相同的?另外,由于我使用 XML api 直接上传到谷歌云存储,这是否意味着我不再需要使用 my-express-endpoint 来处理它并使用例如服务器端的 multer 来处理它?

【问题讨论】:

    标签: javascript reactjs google-cloud-storage antd


    【解决方案1】:

    对于初学者:当您提供 customRequest 时,actiondata 选项属性不适用。因此,您是正确的,您不再需要您的 express 端点,因为您的 express 服务器不参与交易。

    更困难的部分是处理文件对象。当您在表单中使用&lt;input type=file ...&gt; 时(如在您的第一个示例中),幕后会发生一些魔术。

    当您自己创建 XHR 时,您必须自己做这个魔法(实际上是读取文件)。推荐阅读:页面下方三分之二处的“处理二进制数据”部分https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript

    但还有更好的方法。我建议使用为您完成工作的 xhr 包装器。比如https://github.com/axios/axios,可以直接处理你在customRequest中得到的File对象。

    【讨论】:

    • 谢谢,帮了大忙。我认为由于某种原因 XMLHttpRequest 与使用 axios 不同。这让它变得容易多了。
    猜你喜欢
    • 2018-04-24
    • 2021-02-06
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2017-03-27
    • 2019-10-22
    相关资源
    最近更新 更多