用SweetAlert2和ExpressJS上传图像文件

发布于 2025-02-13 13:15:33 字数 3503 浏览 0 评论 0原文

我想使用SweetAlert2和ExpressJS将图像上传到我的服务器。

当我将HTML输入带有名称属性时,它可以正常工作。但是我想与SweetAlert2一起使用,但行之有效。

我使用SweetAlert2文档的示例。而且看来我可以获取图像数据console.log(结果),但我无法将其发送到我的服务器。当我将请求发送到服务器时,console.log(req.file);仍然获取未定义的数据。

我使用“ Fetch API”,因为我不想使用Ajax或jQuery。

我在JSFiddle上上传客户端部分,您可以在此处入住

[客户端零件]

async function start() {
  await Swal.fire({
    title: "Please Select Image File",
    input: "file",
    inputAttributes: {
      accept: "image/*",
      "aria-label": "Select Image",
    },
    showLoaderOnConfirm: true,
    preConfirm: (result) => {
      console.log(result);
      const reader = new FileReader();
      console.log(file);
      reader.onload = (e) => {
        let timerInterval;
        Swal.fire({
          title: "Wait for Upload",
          imageUrl: e.target.result,
          iamgeHeight: 200,
          imageWidth: 200,
          imageAlt: "The uploaded picture",
          didOpen: () => {
            Swal.showLoading();
            return fetch(`${MY_SERVER_URL}`, {
                method: "POST",
                headers: {
                  Accept: "application/json",
                },
                body: reader,
              })
              .then((response) => {
                // console.log(response);
                if (!response.ok) {
                  throw new Error(response.statusText);
                }
                return response.json();
              })
              .catch((error) => {
                Swal.showValidationMessage(
                  `Request failed: ${error}`
                );
              });
          },
          willClose: () => {
            console.log('Nothing')
          },
        }).then((result) => {
          /* Read more about handling dismissals below */
          if (result.dismiss === Swal.DismissReason.timer) {
            console.log("I was closed by the timer");
          }
        });
      };
      reader.readAsDataURL(result);
    },
  });
}

start();
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body>

</body>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</html>

[服务器零件(express.js)]

var express = require("express");
var router = express.Router();
const multer = require("multer");
var storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "./public/images");
  },
  filename: (req, file, cb) => {
    console.log(file);
    var filetype = "";
    if (file.mimetype === "image/gif") {
      filetype = "gif";
    }
    if (file.mimetype === "image/png") {
      filetype = "png";
    }
    if (file.mimetype === "image/jpeg") {
      filetype = "jpg";
    }
    cb(null, "image-" + Date.now() + "." + filetype);
  },
});
var upload = multer({
  storage: storage,
});

router.post("/uploadImage", upload.single("file"), async (req, res, next) => {
  console.log(req.file);
  console.log("good");
  let fileName = req.file.filename;
  res.redirect(
    `${MY_SERVER_URL_REDIRECT_URL}`
  );
});

I want to upload image to my server with SweetAlert2 and Expressjs.

When I use HTML input with name attribute, it works fine. But I want to use with SweetAlert2 and it's not working.

I use SweetAlert2 document's example. And It seems that I can get image data console.log(result) but I cannot send it to my server. When I send request to my server, the console.log(req.file); still get undefined data.

I use 'Fetch API' because I don't want to use Ajax or jQuery.

I upload Client Part on JsFiddle you can check in here

[Client Part]

async function start() {
  await Swal.fire({
    title: "Please Select Image File",
    input: "file",
    inputAttributes: {
      accept: "image/*",
      "aria-label": "Select Image",
    },
    showLoaderOnConfirm: true,
    preConfirm: (result) => {
      console.log(result);
      const reader = new FileReader();
      console.log(file);
      reader.onload = (e) => {
        let timerInterval;
        Swal.fire({
          title: "Wait for Upload",
          imageUrl: e.target.result,
          iamgeHeight: 200,
          imageWidth: 200,
          imageAlt: "The uploaded picture",
          didOpen: () => {
            Swal.showLoading();
            return fetch(`${MY_SERVER_URL}`, {
                method: "POST",
                headers: {
                  Accept: "application/json",
                },
                body: reader,
              })
              .then((response) => {
                // console.log(response);
                if (!response.ok) {
                  throw new Error(response.statusText);
                }
                return response.json();
              })
              .catch((error) => {
                Swal.showValidationMessage(
                  `Request failed: ${error}`
                );
              });
          },
          willClose: () => {
            console.log('Nothing')
          },
        }).then((result) => {
          /* Read more about handling dismissals below */
          if (result.dismiss === Swal.DismissReason.timer) {
            console.log("I was closed by the timer");
          }
        });
      };
      reader.readAsDataURL(result);
    },
  });
}

start();
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body>

</body>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</html>

[Server Part (Express.js)]

var express = require("express");
var router = express.Router();
const multer = require("multer");
var storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "./public/images");
  },
  filename: (req, file, cb) => {
    console.log(file);
    var filetype = "";
    if (file.mimetype === "image/gif") {
      filetype = "gif";
    }
    if (file.mimetype === "image/png") {
      filetype = "png";
    }
    if (file.mimetype === "image/jpeg") {
      filetype = "jpg";
    }
    cb(null, "image-" + Date.now() + "." + filetype);
  },
});
var upload = multer({
  storage: storage,
});

router.post("/uploadImage", upload.single("file"), async (req, res, next) => {
  console.log(req.file);
  console.log("good");
  let fileName = req.file.filename;
  res.redirect(
    `${MY_SERVER_URL_REDIRECT_URL}`
  );
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终止放荡 2025-02-20 13:15:33

您的后端期望一个名为文件的文件

您可以使用formdata

let formdata = new FormData()
formdata.append('file', file)

然后发送它。另请注意,您的请求不是application/json

确保不要设置内容型标头。浏览器将为您设置它,包括边界参数。

fetch(`${MY_SERVER_URL}`, {
   method: "POST",
   body: formdata,
})

Your backend expects an file named file

You can use FormData

let formdata = new FormData()
formdata.append('file', file)

Then you send it. Also to note here, your request isnt application/json.

make sure not to set the Content-Type header. The browser will set it for you, including the boundary parameter.

fetch(`${MY_SERVER_URL}`, {
   method: "POST",
   body: formdata,
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文