express框架,在上传图片功能方面,用formidable里面的incomingform功能,很方便。很多功能都已经封装好了,非常好用,简单,不需要写更深层次的代码了。确实不错。
下面是我自己跟着黑马教程的博客系统的部分,自己写的上传文件的过程。记录一下。
express框架里面,
app.js
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.engine("art", require("express-art-template"));
app.engine("html", require("express-art-template"));
app.set("view engine", "art");
// app.engine("ar", fn)
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use("/", indexRouter);
app.use("/users", usersRouter);
// catch 404 and forward to error handler
// app.use(function (req, res, next) {
// next(createError(404));
// });
// error handler
// app.use(function (err, req, res, next) {
// // set locals, only providing error in development
// res.locals.message = err.message;
// res.locals.error = req.app.get("env") === "development" ? err : {};
// // render the error page
// res.status(err.status || 500);
// // res.render("error");
// // console.log("errors::::");
// // next();
// });
// app.get("/upload", require("./routes/upImg"));
app.get("/upload", function (req, res) {
res.render("index.html");
});
app.post("/upload", require("./routes/upload"));
app.listen(3000, function () {
console.log("server 3000");
});
// module.exports = app;
这里我直接使用的是art模板,比较喜欢art,ejs模板里面的尖括号,实在有点反人类,感觉尖括号阔的人都晕了,还是art更加简洁。另外把一些报错的信息直接给屏蔽掉了,error有的话不再渲染error,直接打印出来,可以更方面调试。
index页面直接就是上传文件和填写表单的页面,因此,直接在index的路由里面,不用管,
接受上传的页面是upload,写在app.js里面了,后面可以封装起来, 不过upload本来就是封装的。
upload文件
upload.js
const formidable = require("formidable");
const path = require("path");
module.exports = (req, res) => {
const form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname, "../", "public", "uploads");
// console.log(form.uploadDir);
//3.保留文件的后缀
form.keepExtensions = true;
// console.log(form);
//4.解析表单
form.parse(req, (err, fields, files) => {
// 1. err是错误对象,如果保存失败,存储蜈信息。/
// 2.fields 对象类型
// 3. files 对象类型,保存了和上传文件相关的数据.
// 4.
console.log("**************");
console.log(
files.cover.originalFilename,
"\n",
files.cover.newFilename
);
extName = files.cover.originalFilename.split(".")[1];
console.log(extName);
// xx =
// res.send();
res.send(files);
});
// res.send("ok");
};
formidable 模块的incomingForm对象可以接受内容包括文字、图片等,当然其他的不知道能不能接受。
另外设置了上传文件的额地址是在public下面的uploads
form.parse,可以解析整个req,拿出req里form表单的内容。表单控件里,可以是input的text,也可以是input的 file
index文件如下:
index.html
<!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">
<title>Document</title>
<link rel="stylesheet" href="/stylesheets/bootstrap.min.css">
<script src="/javascripts/jquery.min.js"></script>
<script src="/javascripts/bootstrap.min.js"></script>
<style>
.form-control {
width: 50%;
}
label {
padding: 10px;
}
</style>
</head>
<body>
<h1>hello
{{ title }}
</h1>
<form action="/upload" class="form-container" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="">标题</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group">
<label for="">作者</label>
<input type="text" name="author" class="form-control">
</div>
<div class="form-group">
<label for="">图片</label>
<input type="file" name="cover" id="file">
<div class="thumbnail-waper">
<img src="" alt="" class="img-thumbnail" id="preview" style="width: 400px; height: auto">
</div>
</div>
<div class="form-group">
<label for="">内容</label>
<textarea name="content" id="content" cols="30" rows="10" class="form-control"></textarea>
</div>
<div class="buttons">
<input type="submit" class="btn btn-primary">
</div>
</form>
<script>
//选择文件上传空间
var file = document.querySelector("#file");
var preview = document.querySelector("#preview")
//当用户选择完文件之后
file.onchange = function() {
var reader = new FileReader();
//代表用户选择的文件列表
// console.log(this.files[0]);
//2.读取文件
reader.readAsDataURL(this.files[0])
// 3. 监听 onload事件
reader.onload = function() {
console.log(reader.result);
preview.src = reader.result
}
}
</script>
</body>
</html>
里面就一个大的form,其实不复杂。
下面,在body上方,插入一段js,主要两个工作,1.接收上传的图片,2.当图片上传完之后,渲染出图片。还是很不错的。
如下图:

今天搞了一天,也算是把express的文件部分弄明白了。感觉学习就是,黑马的视频还是很不错,反复看,做出来一个项目,然后再把项目里面的细节反复做几遍,弄出自己的东西,整体之后,把各个小的知识点再钻研透了。就OK了
2082

被折叠的 条评论
为什么被折叠?



