使用内置 NodeJS `fetch` 在 FormData 中上传文件

问题描述 投票:0回答:1

How to upload file with FormData using Node.JS built-in

fetch
(not
node_fetch
)?

node.js file-upload fetch form-data
1个回答
2
投票

使用 NodeJS 内置

FormData
将文件上传为
fetch
。 我们将文件读取为
Blob
然后
set
append
FormData
对象。 最后我们发送
FormData
对象作为
fetch
请求的主体。

要将文件读取为

Blob
,我们可以使用
fs.openAsBlob
(Node.JS ^19.8)或将文件
fs.readFile
读取为
Buffer
并将其转换为
Blob
.

import { openAsBlob } from 'node:fs' // Node.JS ^19.8
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 = await openAsBlob(filePath); // or
  const file = new Blob([await readFile(filePath)], { type: lookup(filePath) });
  const formData = new FormData()
  formData.set("file", file, "file_name.ext");
  return fetch(`https://example.com/upload`, { method:"POST", body:formData, /* ... */ });
}

© www.soinside.com 2019 - 2024. All rights reserved.