Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Node and MongoDB to build a picture bed or network disk

2025-01-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "how to use Node and MongoDB to build a picture bed or network disk", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use Node and MongoDB to build a picture bed or network disk" article.

1 the origin of the article

This project is relatively simple, after reading the students can quickly build a small net disk or picture bed.

2 start-up 2.1 concept

First of all, we have to understand what the file storage (GridFS) of Mongodb is, because we all store files based on GridFS.

2.2 what do we need?

After understanding the general concept, we can start to install the necessary plug-ins.

Express (I don't need to tell you what this is)

Body-parser (middleware for Node parsing body)

Ejs (template engine, rapid development will not separate the front and back ends, and interested partners can use Vue/React to build small network disks)

Gridfs-stream (easily transfer files to and from MongoDB GridFS. )

Method-override (we use the form form to upload simply, because the form form does not support put/delete request, so arrange it, the partner can use Ajax on their own, so there is no need for so much trouble.)

Mongoose (an essential plug-in for connecting to mongodb)

Multer (Multer is node.js middleware for dealing with multi-part / form data, mainly for uploading files. It is written on top of busboy for maximum efficiency.)

Multer-gridfs-storage (Multer's GridFS storage engine stores uploaded files directly to MongoDb.)

Nodemon (Hot Update)

(recommended tutorial: getting started with Node)

That's what we need to prepare.

Npm install express body-parser ejs gridfs-stream method-override mongoose multer multer-gridfs-storage / / or yarn add express body-parser ejs gridfs-stream method-override mongoose multer multer-gridfs-storage

2.3 initialize a project

/ / additional information can be provided by yourself / / npm init

Then create a new entry file app.js and page views/index.ejs in the root directory

3 now the project has started 3.1 finish the basic part first

Bring in the package we installed and take a look.

Const express = require ('express') const path = require (' path') const crypto = require ('crypto') const mongoose = require (' mongoose') const multer = require ('multer') const GridFsStorage = require (' multer-gridfs-storage') const GridFsStream = require ('gridfs-stream') const methodOverride = require (' method-override') const bodyParser = require ('body-parser')

Const app = express () app.set ('view engine',' ejs') / / set template engine app.use (bodyParser.json ()) app.use (methodOverride ('_ method')) app.get ('/', (req, res) = > {res.render ('index')}) const port = 5000app.listen (port, () = > {console.log (`App listering on port ${port} `)})

Generally speaking, if app.js is started, we can see the interface in views/index.ejs when we visit http://localhost:5000 in the browser. If not, check whether the console reports an error.

3.2Connect to our Mongodb database

The local mongodb database I use here is the same online. We can use NoSQL manager for mongdb to view the data in our database. Let's create a new collection, which is called grid_uploads. So if you connect, you will also connect to this collection.

/ / Link to the database const mongoURL = 'mongodb://localhost:27017/grid_uploads'

Const connect = mongoose.createConnection (mongoURL, {useNewUrlParser: true, useUnifiedTopology: true}) 3.3 beautify the interface (views/index.ejs)

As a front-end engineer for two years, we have already developed pixel eyes. We certainly can't make the interface hot or ugly, right? we can't get through, so let's simply use bootstrap4 to make an interface.

File upload img {width: 100% } Mongo File upload Select File 3.4 do some necessary processing

/ / define gfs variable. When we operate database files later, we can't do without let gfs. Connect.once ('open', () = > {/ / listen on the database, control the access of files through gridfs-stream middleware and database gfs = GridFsStream (connect.db, mongoose.mongo) gfs.collection (' upload') / / it will set up upload.files (record file information) upload.chunks (storage file block)} in our database)

/ / using multer-gridfs-storage Multer middleware, the attachments we uploaded are directly stored in MongoDbconst storage = new GridFsStorage ({url: mongoURL, file: (req, file) = > {return new Promise ((resolve, reject) = > {/ / the following comments are renamed to the file. If you want the original file name, you can use file.originalname to return it. / / it is recommended that partners who have time store two documents, one record original file name and one record encrypted file name Then when you return to the page, you can return the Chinese name to / / crypto.randomBytes (16, (err) Buf) = > {/ / if (err) {/ / return reject (err) / / const filename = buf.toString ('hex') + path.extname (file.originalname) / / const fileinfo = {/ / filename / / bucketName: 'upload' / /} / / resolve (fileinfo) / /}) const fileinfo = {filename: new Date () +' -'+ file.originalname BucketName: 'upload'} resolve (fileinfo)}) const upload = multer ({storage}) 3.5 write the interface where we upload the first file

App.post ('/ upload', upload.single ('file'), (req, res) = > {res.redirect (' /')})

It seems simple. Please remember a few things.

In views/index.ejs (the name specified by input type=file must be the same as the upload.single ('file') of the interface

After uploading the file, we redirect back to our home page, and then we can see that our two documents have data on NoSql.

3.6 get all our file information

Get all our files.

App.get ('/ files', (req, res) = > {/ / return an array object to gfs.files.find (). ToArray ((err, files) = > {if (! files | | files.length = 0) {return res.status (404) .json ({err: 'file does not exist!' })} return res.json (files)})})

We can do some beautification operations, for example, we can upload a picture, return to the interface and display it as a picture, and the rest in the format of a tag (which can be downloaded), so we can beautify the views/index.ejs interface (ejs syntax is really troublesome to use), relayout and add delete buttons.

File upload img {width: 100%;} Mongo file upload selected file

Delete file does not exist

To get the files variable in ejs, we should rewrite the get ('/') interface to read the database file information and output it to the page when accessing localhost:5000.

App.get ('/', (req, res) = > {gfs.files.find (). ToArray ((err, files) = > {if (! files | | files.length = 0) {res.render ('index', {files: false}) return} files.map (file = > {/ / if the following image types are displayed at the front end, the rest will be treated as attachments Distinguish between pictures and non-pictures by isImage const imageType = ['image/png',' image/jpg', 'image/gif',' image/jpeg'] if (imageType.includes (file.contentType)) {file.isImage = true} else {file.isImage = false}}) res.render ('index', {files: files})

3.7 single file download

Here we access the / download/:filename interface through the a tag. Filename is the file name. Of course, you can use other things such as _ id. When the attachment is found, it will be merged into readable retention and returned through the pipeline, so that you can download it directly by clicking the file title on the front-end interface.

App.get ('/ download/:filename', (req, res) = > {gfs.files.findOne ({filename: req.params.filename}, (err, file) = > {if (! file) {return res.status (404). Json ({err: 'file does not exist!' })} const readstream = gfs.createReadStream (file.filename) readstream.pipe (res)})})

3.8 single file deletion

Here we access the / files/:id interface through the a tag, corresponding to id, click the delete button, delete it directly, and redirect to the home page.

App.delete ('/ files/:id', (req, res) = > {gfs.remove ({_ id: req.params.id, root: 'upload'}, (err) = > {if (err) {return res.status (404). Json ({err:' deleted file does not exist!' })} res.redirect ('/')})})

Because we have been using form to do the request, but the form form does not have the delete request method, so we used the method-override plug-in, of course, if you use Ajax, it does not matter, after all, our project is quick, mainly depends on the effect and process.

The above is about the content of this article on "how to use Node and MongoDB to build a picture bed or network disk". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report