Express builds a photo storage website 2-upload and display files
The image data stored in the static data used in the previous section, this section adds the following functions
1 – upload files
2 – display files
Static resource display picture
The path to the static resource file is specified in app.js
app.use(express.static(path.join(__dirname, 'public')));
With this line of settings, you can access the static resources under the public folder.
There are several pictures under public/images under the project directory. After starting the service, visit the corresponding address to display the pictures. For example, the name of the picture is 1669269355053_1.png, and the browser access
http://127.0.0.1:3000/images/1669269355053_1.png
The photo page displays the pictures under the folder
Modify photo.js under the routes file
var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var fs = require('fs');
var destpath = "./public/images/";
var urlpath = "/images/";
// photos.push({
// 'name': 'photo1',
// 'path': '/images/abd3c3ec-922c-11e7-8a20-0242ac11000c.png'
// });
// photos.push({
// 'name': 'photo2',
// 'path': '/images/6db31128-39dd-11e7-895e-0242ac110016.png'
// });
/* GET photo page. */
router.get('/', function (req, res, next) {
let arr = fs.readdir(destpath, function(err, files) {
if (err) {
console.log('读取文件夹错误:', err);
} else {
var photos = [];
files.forEach(fileName => {
let item = {
'name':'',
'path':''
};
item.name = findFileName(fileName);
item.path = urlpath + fileName;
photos.push(item);
});
res.render('photos', {
title: 'Photos', data: photos });
}
});
});
function findFileType(originalFilename) {
var lastIndex = originalFilename.lastIndexOf('.');
if (lastIndex != -1) {
return originalFilename.substring(lastIndex);
}
return originalFilename;
}
function findFileName(inputFileName) {
var lastIndex = inputFileName.lastIndexOf('.');
if (lastIndex != -1) {
return inputFileName.substring(0, lastIndex);
}
return inputFileName;
}
module.exports = router;
Show all pictures in the folder
router.get('/', function (req, res, next) {
let arr = fs.readdir(destpath, function(err, files) {
if (err) {
console.log('读取文件夹错误:', err);
} else {
var photos = [];
files.forEach(fileName => {
let item = {
'name':'',
'path':''
};
item.name = findFileName(fileName);
item.path = urlpath + fileName;
photos.push(item);
});
res.render('photos', {
title: 'Photos', data: photos });
}
});
});
- Use the fs module to read all files under the specified folder
- Splice the image name with the prefix /images/ of the static resource as the src data of the img tag
- Output data to the views/photos/index.ejs view
res.render('photos', {
title: 'Photos', data: photos });
Start the service, access
http://127.0.0.1:3000/photo
Shows all the images under the images folder
upload files
Add route to upload page
- Modify photo.js, add the following code
router.get('/upload', function (req, res, next) {
res.render('photos/upload', {
title: '图片上传' });
});
- Add the page upload.ejs corresponding to the route
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>图片上传</p>
<form method="post" enctype="multipart/form-data" action="/photo/submit" >
<p><input type="text" name="name", placeholder="Name" /></p>
<p><input type="file" name="file" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
To write a form form to upload a file, you need to specify the enctype attribute of the form form as multipart/form-data, and when you click submit, the /photo/submit interface in the background will be called
Add the routing of the submission interface
Modify photo.js
- First introduce the multiparty module to parse the form
var multiparty = require('multiparty');
- Add /submit route
router.post('/submit', function (req, res, next) {
var form = new multiparty.Form();
form.encoding = 'utf-8';
form.uploadDir = destpath;
form.maxFilesSize = 20 * 1024 * 1024;
form.parse(req, (err, fields, files) => {
if (err) {
console.log('解析上传文件错误:', err);
} else {
var originalFilename = files.file[0].originalFilename;
var fileType = findFileType(originalFilename);
var fileName = originalFilename;
if (fields.name != null) {
fileName = fields.name[0] + fileType;
}
var uploadedPath = files.file[0].path;
var newFileName = destpath + new Date().getTime() + "_" + fileName;
fs.rename(uploadedPath, newFileName, (err) => {
if (err) {
console.log('重命名文件错误:', err);
throw err;
}
res.redirect('/photo');
});
}
});
});
The first step: parse the form form
var form = new multiparty.Form();
form.encoding = 'utf-8';
form.uploadDir = destpath;
form.maxFilesSize = 20 * 1024 * 1024;
form.parse(req, (err, fields, files) => {
}));
Step 2: Rename the file, rename it with the name received by the form
fs.rename(uploadedPath, newFileName, (err) => {
});
Step 3: Redirect to the image display page
res.redirect('/photo');
Website renderings
- start service
F:\Github\Nodejs\photo>npm start
> [email protected] start
> node ./bin/www
- browser access
http://127.0.0.1:3000/photo
3. Click upload to jump to the form upload page
4. After filling out the form, click upload to redirect to the home page