未加星标

File Upload With Multer in Node.js and Express

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

When a web client uploads a file to a server, it is generally submitted through a form and encoded as multipart/form-data .Multer is middleware for Express and Node.js that makes it easy to handle this multipart/form-data when your users upload files. In this tutorial, I'll show you how to use this library to handle different file upload situations in Node.

How Does Multer Work?

As I said above, Multer is Express middleware. Middleware is a piece of software that connects different applications or software component. In Express, middleware processes and transforms incoming requests to the server. In our case, Multer acts as a helper when uploading files.

Project Setup

We will be using the Node Express framework for this project. Of course, you'll need to have Node installed.

Create a directory for our project, navigate into the directoryand issue npm init to create a .json file that manages all the dependencies for our application.

mkdir upload-express
cd upload-express
npm init

Next, install Multer, Express and the other necessary dependencies necessary to bootstrap an express app.

npm install express multer body-parser --save

Next, create a server.js file.

touch server.js

Then, in server.js , we will initialize all the modules, create an express app and create a server for connecting to browsers.

// call all the required packages
const express = require('express')
const bodyParser= require('body-parser')
const multer = require('multer');
app.use(bodyParser.urlencoded({extended: true}))
const app = express()
//CREATE EXPRESS APP
const app = express();
//ROUTES WILL GO HERE
app.get('/', function(req, res) {
res.json({ message: 'WELCOME' });
});
app.listen(3000, () => console.log('Server started on port 3000'));

Running node server.js and navigating to localhost:3000 on your browser should give you the following message.


File Upload With Multer in Node.js and Express
Create the Client Code

The next thing will be to create an index.html file to write all the code that will be served to the client.

touch index.html

This file will contain the differentforms that we will use for uploading our different file types.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MY APP</title>
</head>
<body>
<!-- SINGLE FILE -->
<form action="/uploadfile" enctype="multipart/form-data" method="POST">
<input type="file" name="myFile" />
<input type="submit" value="Upload a file"/>
</form>
<!-- MULTIPLE FILES -->
<form action="/uploadmultiple" enctype="multipart/form-data" method="POST">
Select images: <input type="file" name="myFiles" multiple>
<input type="submit" value="Upload your files"/>
</form>
<!-- PHOTO-->
<form action="/upload/photo" enctype="multipart/form-data" method="POST">
<input type="file" name="myImage" accept="image/*" />
<input type="submit" value="Upload Photo"/>
</form>
</body>
</html>

Open server.js andwrite a GET route that rendersthe index.html file instead of the "WELCOME" message.

// ROUTES
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
}); Multer storage

The next thing will be to define a storage location for our files. Multer gives the option of storing files to disk as shown below. Here we set up a directory where all our files will be saved and we'll also give the files a new identifier.

//server.js
// SET STORAGE
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage }) Handling File Uploads Uploading a Single File

In the index.html file, we defined an action attribute that performs a POST request. Now we need to create an endpoint in the Express application. Open the server.js file and add the following code:

app.post('/uploadfile', upload.single('myFile'), (req, res, next) => {
const file = req.file
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send(file)
})

Note that the name of the file field should be the same as the myFile argument passed to the upload.single function.

Uploading Multiple Files

Uploading multiple files with Multer is similar to a single file upload but a few changes.

//Uploading multiple files
app.post('/uploadmultiple', upload.array('myFiles', 12), (req, res, next) => {
const files = req.files
if (!files) {
const error = new Error('Please choose files')
error.httpStatusCode = 400
return next(error)
}
res.send(files)
}) Uploading Images

Instead of saving uploaded images to the file system, we will store them in a MongoDB database so that we can retrieve them later as needed. But first, let's install MongoDB.

npm install mongodb --save

We will then connect to MongoDB through the Mongo.client method and then add the MongoDB URL to that method. You can use a cloud service like Mlab which offers a free plan or simply use the locally available connection.

const MongoClient = require('mongodb').MongoClient
const myurl = 'mongodb://localhost:27017';
MongoClient.connect(myurl, (err, client) => {
if (err) return console.log(err)
db = client.db('test')
app.listen(3000, () => {
console.log('listening on 3000')
})
})

Open server.js and define a POST request that enables saving images to the database.

app.post('/uploadphoto', upload.single('picture'), (req, res) => {
var img = fs.readFileSync(req.file.path);
var encode_image = img.toString('base64');
// Define a JSONobject for the image attributes for saving to database
var finalImg = {
contentType: req.file.mimetype,
image: new Buffer(encode_image, 'base64')
};
db.collection('quotes').insertOne(finalImg, (err, result) => {
console.log(result)
if (err) return console.log(err)
console.log('saved to database')
res.redirect('/')
})
})

In the above code, we first encode the image to a base64 string, construct a new buffer from the base64 encoded string and then save it to our databasecollection in JSON format.

We then display a success message and redirect the user to the index page.

RetrievingStored Images

To retrieve the stored images, we perform a mongodb search using the find method and return an array of results. We then go on and obtain the _id attributes of all the images and return them to the user.

app.get('/photos', (req, res) => {
db.collection('mycollection').find().toArray((err, result) => {
const imgArray= result.map(element => element._id);
console.log(imgArray);
if (err) return console.log(err)
res.send(imgArray)
})
}); Since we already know the id's of the images, we can v

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

分页:12
转载请注明
本文标题:File Upload With Multer in Node.js and Express
本站链接:https://www.codesec.net/view/611841.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(10)