Надеюсь, у вас все хорошо.
У меня проблемы с кодом, я пытаюсь сохранить изображение, которое будет загружено пользователем при регистрации пользователя.
I затем хотите просмотреть изображение, загруженное пользователем, в папке ./uploads.
Я закомментировал код, который нарушает мой сайт. Я следил за примерами онлайн, но не повезло.
Приложение. js
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
flash = require("connect-flash"),
passport = require("passport"),
fs = require('fs');
LocalStrategy = require("passport-local"),
methodOverride = require("method-override"),
Pet = require("./models/pet"),
User = require("./models/user"),
Schema = mongoose.Schema,
seedDB = require("./seeds")
const port = process.env.PORT || 27017;
//requiring routes
var petsRoutes = require("./routes/pets"),
indexRoutes = require("./routes/index")
mongoose.connect("mongodb://localhost:27017/db", {
useNewUrlParser: true
});
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
app.use(flash());
// seedDB(); //seeding
//Passport
app.use(require("express-session")({
secret: "pets",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.error = req.flash("error");
res.locals.success = req.flash("success");
next();
});
app.use("/", indexRoutes);
app.use("/pets", petsRoutes);
app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
cb(null, Date.now() + file.originalname);
}
});
// app.post(‘/register’, function (req, res) {
// var newUser = new User();
// userSchema.profileimage.data = fs.readFileSync(req.files.userPhoto.path)
// userSchema.profileimage.contentType = ‘image / jpg’;
// userSchema.save();
// });
Пользователь. js
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
email: String,
profileimage: {data: Buffer, contentType: String},
password: String
});
UserSchema.plugin(passportLocalMongoose)
// app.use(multer({
// dest: ‘./uploads/ ’,
// rename: function (fieldname, filename) {
// return filename;
// },
// }));
module.exports = mongoose.model("User", UserSchema);
Указатель. Js
var express = require("express");
var router = express.Router();
var passport = require("passport");
var User = require("../models/user");
//root route
router.get("/", function(req, res){
res.render("landing");
});
// show register form
router.get("/register", function(req, res){
res.render("register");
});
// show contact page
router.get("/contact", function (req, res) {
res.render("contact");
});
// show about page
router.get("/about", function (req, res) {
res.render("about");
});
//handle sign up logic
router.post("/register", function(req, res){
var username = req.body.username;
var email = req.body.email;
var profileimage = req.body.profileimage;
var newUser = new User({username: username, email: email, profileimage: profileimage});
User.register(newUser, req.body.password, function(err, user){
if(err){
req.flash("error", err.message);
return res.render("register");
}
passport.authenticate("local")(req, res, function(){
req.flash("success", "Come adopt a Pet " + user.username);
res.redirect("/pets");
});
});
});
//show login form
router.get("/login", function(req, res){
res.render("login");
});
//handling login logic
router.post("/login", passport.authenticate("local",
{
successRedirect: "/pets",
failureRedirect: "/login"
}), function(req, res){
});
// logout route
router.get("/logout", function(req, res){
req.logout();
req.flash("success", "Logged you out!");
res.redirect("/pets");
});
module.exports = router;
registration.e js
<% include ./partials/header %>
<div class="container"></div>
<form action="/register" method="POST" class="form-signin" enctype="multipart/form-data">
<!-- username -->
<label for="inputUsername" class="sr-only">Username</label>
<input type="text" id="inputUsername" class="form-control" placeholder="Org Name or Personal Name" name="username" required>
<!-- email -->
<input type="email" id="inputEmail" class="form-control" placeholder="Email" name="email" required>
<!-- password -->
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" name="password" required>
<p>Org - Upload Legal Documentation</p>
<input type="file" id="inputImage" class="form-control" name="profileimage">
<!-- submit -->
<button class="btn btn-lg btn-primary btn-block" type="submit" name="submit" , value="signup">Sign up</button>
</form>
</div>
<% include ./partials/footer %>