Reputation:
I need to upload an image to the server (built in nodejs) and display it for everyone in the html site. 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
Upvotes: 1
Views: 4450
Reputation: 1
just upload an image to the server (built in nodejs) but not display it yet, here it works for me.
app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const path = require("path");
const bodyParser = require("body-parser");
//var cors = require('cors');
const multer = require("multer");
let ejs = require('ejs');
// const postRoutes = require("./routes/post");
const something = require('./model/post');
const db = mongoose.connect("mongodb://localhost:27017/user",{
useNewUrlParser: true,
useUnifiedTopology: true
}).then(db => {
console.log('MongoDB database connected');})
.catch((error) => {
console.log(error);})
mongoose.Promise = global.Promise;
app.use(express.static('public'));
//For parsing application/json
app.use(express.json());
// For parsing application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// app.use(cors({
// origin: [
// 'http://localhost:3000'
// ],
// credentials: true
// }));
// // app.use(cookieParser());
// app.use(cors());
// // app.use(fileUpload({
// // useTempFiles:true
// // }));
app.set("views", path.join(__dirname, "views"));
app.set('view engine', 'ejs');
//app.use("/", express.static(path.join("public", 'index.html')));
app.use(express.static(__dirname + "public"));
// const cheer = require("./controller/post");
// on cree notre dictionnaire
const MIME_TYPES = {
'image/jpg': 'jpg',
'image/jpeg': 'jpeg',
'image/png': 'png',
'image/gif': 'gif',
'video/mp4': 'mp4',
'video/x-msvideo': 'avi',
'video/mp4': 'mp4',
'video/mpeg': 'mpeg',
'video/ogg': 'ogv',
'video/mp2t': 'ts',
'video/webm': 'webm',
'video/3gpp': '3gp',
'video/3gpp2': '3g2'
};
//on indique le chemin d'acces des images a mutler
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, "public/uploads");
},
filename: (req, file, callback) => {
const name = file.originalname.split(' ').join('_');
const extension = MIME_TYPES[file.mimetype];
callback(null, name);
// const name = file.originalname.split(' ').join('_');
// //const extension = MIME_TYPES[file.mimetype];
// callback(null, name + path.extname(file.originalname));
}
});
// on exporte notre module
const temp = multer({
storage: storage
}).single("image");
//save to database. /api/movies/
app.post("/api/movies", temp, async (req, res)=>{
var newMovie = new something({
"image": req.file.filename
// likers: "req.body.likers",
// comments: "req.body.comments"
});
console.log(newMovie.image);
try {
const savedMovie = await newMovie.save();
//res.status(201).json(savedMovie);
res.render("index", {newMovie: newMovie});
} catch (err) {
res.status(500).json(err);
}
});
// app.get("/square.png", (req, res) => {
// res.sendFile(path.join(__dirname, `public/uploads/square.png`));
// });
app.listen(3000, function(){
console.log('Node js Express js Tutorial at port', 3000);
});
post.js
// on importe mongoose
const mongoose = require('mongoose');
// On cree nos schemats de donnes
const PostSchema = mongoose.Schema(
{
userId: { type: String, required: true },
message: { type: String, trim: true, maxlength: 500 },
picture: { type: String },
video: { type: String },
likers: { type: [String], required: true },
comments: {
type: [
{
commenterId: String,
commenterPseudo: String,
text: String,
timestamp: Number,
}
],
required: true,
},
},
{
timestamps: true,
},
{collection: "notes"}
);
const MovieSchema = mongoose.Schema({
image: {
type: String,
required: true
}
//{collection: "Movie"}
});
module.exports = mongoose.model("notes", MovieSchema);
// module.exports = mongoose.model('Post', PostSchema);
// const silence = new postModel({message: "silence"});
// console.log(silence.message);
Upvotes: 0
Reputation: 978
There are many tutorials and npm packages are available for upload file using nodejs
Here you can find a tutorial
Upvotes: 3
Reputation: 1289
hope this helps
in this example if you pass id and folder same the file gets replaced, change as per your requirements
I have used multer
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;
Upvotes: 2