尝试将图像从浏览器上传到 node.js 服务器......图像没有到达那里......?

编程入门 行业动态 更新时间:2024-10-05 09:33:06

尝试将<a href=https://www.elefans.com/category/jswz/34/1771430.html style=图像从浏览器上传到 node.js 服务器......图像没有到达那里......?"/>

尝试将图像从浏览器上传到 node.js 服务器......图像没有到达那里......?

浏览器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)
  }
}

当我尝试记录 req.files 的内容时,我得到 *undefined *

我已经花了几个小时了。请帮助我

尝试了很多更改并通过谷歌搜索解决方案,但此时无法弄清楚问题所在。

需要帮助

回答如下:

更多推荐

尝试将图像从浏览器上传到 node.js 服务器......图像没有到达那里......?

本文发布于:2024-05-30 10:50:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770417.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像   器上   服务器   node   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!