用SweetAlert2和ExpressJS上传图像文件
我想使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的后端期望一个名为
文件
的文件您可以使用
formdata
然后发送它。另请注意,您的请求不是
application/json
。确保不要设置内容型标头。浏览器将为您设置它,包括边界参数。
Your backend expects an file named
file
You can use
FormData
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.