【问题标题】:Upload file in FormData with builtin NodeJS `fetch`使用内置 NodeJS `fetch` 在 FormData 中上传文件
【发布时间】:2022-11-08 11:53:12
【问题描述】:

如何使用 Node.JS 内置 fetch(不是 node_fetch)上传带有 FormData 的文件?

【问题讨论】:

    标签: node.js file-upload fetch form-data


    【解决方案1】:

    使用fetch 内置的 Node JS 将文件作为表单数据上传。

    import { readFile } from "node:fs/promises"
    import { lookup } from "mime-types"
    
    uploadFile("./path/to/file.ext").then(res => res.text()).then(console.info)
    
    async function uploadFile(/** @type {string} */ filePath) {
      const file = new Blob([await readFile(filePath)], { type: lookup(x) });
      const formData = new FormData()
      formData.set("file", file, "file_name.ext");
      return fetch(`https://example.com/upload`, { method:"POST", body:formData, /* ... */ });
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-10
      • 2023-03-21
      • 2020-06-22
      • 2017-08-30
      • 2022-10-03
      • 2013-12-04
      • 1970-01-01
      • 2020-03-04
      相关资源
      最近更新 更多