如何在express中读取“文件”对象(非本地文件)的内容?

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

我想保存用户输入(包括文件输入)并使用 fetch 发布该对象,如下所示:

// ...
subBtn.addEventListener('click', requestCreate);

async function requestCreate(e) {

  e.preventDefault();

  try {

    const obj = {

      method: "POST",

      headers: { 'Content-Type': 'application/json' },

      body: `{"title": "${name.value}", "body": "${email.value}", "file": "${file.files[0]}", "file2": "${file.files[1]}"}`
    }

    const res = await fetch('http://localhost:3000/', obj);

    if (!res.ok) throw Error(res.statusText);

  } catch (error) { console.log(error) }
}

但是我无法访问后端的文件

app.post('/', (req, res)=> {

  console.log(req.body.file) // returns [object File]
  res.send({name: 'hello world'});
})

app.use(express.json())

我用谷歌搜索了一整天,但没有找到任何有帮助的东西。我觉得我使用 fetch 错误的方式上传文件

有人可以解释一下,如果我可以在不使用 formData 对象的情况下将文件上传到后端吗?不推荐吗?

node.js express fetch-api
1个回答
0
投票

正如“Gabriel Freitas Yamamoto”在评论中提到的,您可以通过 inputElement.files 访问输入文件,但实际上无法使用 json 发送它。发送

file.files[0]
对象将被转换为字符串“[object File]”。

因此您需要将文件转换为 base64 字符串并将其作为字符串发送,或者将文件作为多部分 formData 发送

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