如何使用前端脚本将HTML5 FormData对象转换为原始有效负载?

在我的浏览器端脚本中,我希望获取整个POST请求负载流。

但是,当正文是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包?


解决方案

我不确定它是否真的有助于您的最终目标,但根据您的要求,您可以从此FormData创建一个新的Response对象并将其作为纯文本使用:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
(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() );
})();

相关文章