代码之家  ›  专栏  ›  技术社区  ›  Alfred Huang

如何使用前端javascript将HTML5 FormData对象转换为原始负载?

  •  0
  • Alfred Huang  · 技术社区  · 4 年前

    但是,当主体是一个FormData对象时,特别是当它包含一个文件blob时,有没有简单的方法来创建它?

    这样做的原因是我想使用axios请求拦截器对整个请求体进行AES加密。

    例如:

    我要转换FormData对象:

    const fd = new FormData()
    fd.append('example.png', file) // here file is a file object from the file input object
    

    分为以下内容:

    ------WebKitFormBoundaryMV9GYQ2pcwRJ6XAA
    Content-Disposition: form-data; name="image"; filename="example.png"
    Content-Type: image/png
    <<blob bytes>>
    
    ------WebKitFormBoundaryMV9GYQ2pcwRJ6XAA--
    

    有没有什么简单的方法,使它或任何现有的npm包?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Kaiido    4 年前

    我不确定这是否真的有助于你的最终目标,但对于你所要求的,你可以创造一个新的目标 Response

    (async () => {
      const file = await new Promise((res) => document.createElement('canvas').toBlob(res));
      const fd = new FormData();
      fd.append('example.png', file, 'example.png');
      const resp = new Response(fd);
      console.log( await resp.text() );
    })();