[英]How to upload, display and erase images using node.js and express
I need to upload an image to the server (built in nodejs) and display it for everyone in the html site. 我需要将图像上传到服务器(内置于nodejs中),并在html站点中向所有人显示。 When someone does the same thing the last image can go away I don't need to store it.
当某人做同样的事情时,最后一张图像可能消失了,我不需要存储它。 Anyone can help me with this?
有人可以帮我吗? Best
最好
hope this helps 希望这可以帮助
in this example if you pass id and folder same the file gets replaced, change as per your requirements 在此示例中,如果您传递的ID和文件夹相同,则文件将被替换,请根据需要进行更改
const router = express.Router();
const path = require("path");
const fs = require('fs');
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
router.get('/:folder/:id', async (req, res) => {
let filepath = path.join(__dirname + `/../images/${req.params.folder}/${req.params.id}.png`);
res.sendFile(filepath);
});
const upload = async (image, folder, id) => {
let dir = `images`;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
dir = `images/${folder}`;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
await image.mv(`images/${folder}/${id}.png`);
return `${config.DOMAIN}/images/${folder}/${id}`;
}
router.post('/:folder/:id', upload.single('file'), async (req, res) => {
try {
let image = req.files.image;
if (!image)
return res.status(400).send({ message: 'Image not provided!' });
const imageUrl = await upload(image, req.params.folder, req.params.id);
if (imageUrl)
res.status(201).send({ message: "Image uploaded", url: imageUrl });
} catch (e) {
res.status(400).send({ message: "Error uploading image!", error: e.toString(), req: req.body });
}
});
router.delete('/:folder/:id', async (req, res) => {
try {
fs.unlinkSync(`images/${req.params.folder}/${req.params.id}.png`);
res.status(201).send({ message: "Image deleted" });
} catch (e) {
res.status(400).send({ message: "Error deleting image!", error: e.toString(), req: req.body });
}
});
module.exports = router;
There are many tutorials and npm packages are available for upload file using nodejs 有很多教程,npm包可用于使用nodejs上传文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.