2024年03月30日 建站教程
如何利用nodejs语法实现一个文件夹上传功能,下面web建站小编给大家简单介绍一下具体实现代码!
第一步,创建表单
<form action="/uploadFolder" method="POST" enctype="multipart/form-data"> <input type="file" name="folder[]" multiple webkitdirectory directory> <input type="submit" value="上传"> </form>
第二步,创建路由
const express = require("express"); const multer = require("multer"); const app = express(); const upload = multer({ dest: "uploads/" }); app.post("/uploadFolder", upload.any(), (req, res) => { console.log(req.files); res.send("上传成功"); }); app.listen(3000, () => { console.log("应用程序已启动"); });
第三步,处理上传的文件
const fs = require("fs"); const files = req.files; for (let i = 0; i < files.length; i++) { const file = files[i]; const filePath = file.path; const originalName = file.originalname; const fileName = originalName.replace(/[^a-z0-9]/gi, "_").toLowerCase(); const destPath = "uploads/" + fileName; try { fs.renameSync(filePath, destPath); } catch (err) { res.status(500).send('文件上传失败'); } } res.send("上传成功");
最后,启动应用程序命令
node app.js
本文链接:http://so.lmcjl.com/news/720/