javascript 正在尝试将图像从浏览器上载到节点,js服务器...图像没有到达那里,...

6ioyuze2  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(88)

浏览器Javascript:

const uploadFile = (file) => {
  // add the file to the FormData object
  const fd = new FormData();
  fd.append("avatar", file);

  // send `POST` request
  fetch("http://localhost:3001/uploadtoazure", {
    method: "POST",
    body: fd,
  })
    .then((res) => res.json())
    .then((json) => console.log(json))
    .catch((err) => console.error(err));
};

// select file input
const input = document.getElementById("upload");

// add event listener
input.addEventListener("change", () => {
  uploadFile(input.files[0]);
});

服务器路由器处理程序:

async function uploadToAzure(req, res, next) {

  try {
    console.log(req.files);
    if (!req.files) {
      res.send({
        status: false,
        message: 'No file uploaded'
      })
    } else {
      // Use the name of the input field (i.e. "avatar") to retrieve the uploaded file
      let avatar = req.files.avatar

      // Use the mv() method to place the file in the upload directory (i.e. "uploads")
      avatar.mv('./uploads/' + avatar.name)

      //send response
      res.send({
        status: true,
        message: 'File is uploaded',
        data: {
          name: avatar.name,
          mimetype: avatar.mimetype,
          size: avatar.size
        }
      })
    }
  } catch (err) {
    res.status(500).send(err)
  }
}

当我试图记录请求的内容时,我得到了 *undefined *。文件
我已经花了几个小时了。请帮帮我
尝试了很多变化和谷歌的解决方案,但不能找出什么是错误的,在这一点上。
需要帮助吗

hmmo2u0o

hmmo2u0o1#

使用express-fileupload中间件解决。谢谢你的帮助。

相关问题