On a -node.js learning (14) -nodejs template engine ejs
We learned in the previous section to learn the template engine, this section of our school file upload.
Directory structure is as follows:
1. Upload multer
( )
We add the following code upload.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传demo</title>
</head>
<body>
<form action="http://localhost:8080/infor" method="post" target="stop" enctype="multipart/form-data">
<input type="value" name='account'>
<input type="file" name='user'>
<input type="submit" value="上传">
</form>
<!-- 阻止提交跳转页面 -->
<iframe name="stop" style="display:none;"></iframe>
</body>
</html>
Add the following code server.js
const express=require('express');
const multer=require('multer');
// const bodyParser=require('body-parser');
const server=express();
// server.use(bodyParser.urlencoded())
var objMulter=multer({dest: './uploadImages'}); //设置上传的的图片保存目录
server.use(objMulter.any());
server.post('/infor',function(req,res,next){
console.log(req.body,req.files)
res.send({
code:1,
msg:'成功'
})
})
server.listen(8080);
- When we use the form to submit data, if the data required to be submitted contains images, audio and video, you need to add to the form
enctype="multipart/form-data"
property, if not, the default orderenctype="application/x-www-form-urlencoded"
code transmission. If you need to know the details of the property, you can search online to understand. Embodied in the Content-Type header of the request, such as
- Earlier we talked about body-parser component can only handle
enctype="application/x-www-form-urlencoded"
data encoded and placedreq.body
in, so if it contains images and other data, need the help of the middleware, where the usemulter
of middleware. -
multer({dest: './uploadImages'})
It said it will upload the picture transfer to a specified folder (where to uploadImages example, if not the folder will be automatically generated), if you do not add a dest attribute, these files will be stored in memory and never written to disk. -
objMulter.any()
Represents any uploaded data received, there is a correspondingobjMulter.single('user')
(represented only receives the user name of the uploaded data), the present embodiment usingobjMulter.any()
the received upload any data. - multer will upload the file information is written
req.file
in the form of text information into the fieldsreq.body
of (and does not require the introduction of body-parser)
We tested under the following:
I have to copy the data to print out the screenshot below:
//req.body
{ account: 'eee' }
//req.files
[{
fieldname: 'user', //表单的name属性值
originalname: '五月排行榜.png', //上传的图片原始文件名(含后缀)
encoding: '7bit', //文件编码
mimetype: 'image/png', //上传图片格式(MIME 类型)
destination: './www/uploadImages', //上传后的相对图片路径(不包含文件)
filename: 'db5debb87b20a324a36b618f27441fca', //上传的图片新生成的文件名(不含后缀)
path: 'www\\uploadImages\\db5debb87b20a324a36b618f27441fca', //上传后的完整图片路径(包含文件)
size: 1182425 //上传图片大小
}]
So far, we have completed a simple file upload. But because they do not contain file upload file suffix, so can not be previewed, then how can you add a suffix to upload pictures of it? Before adding a suffix, we first understandpath模块(获取后缀)与fs模块(重写文件名)
2.path module
New path.js file, add the following code:
const path=require('path');
const file1='/home/user/dir/file.txt';
const str=path.parse(file1)
console.log(str)
Run path.js output:
{
root: '/',
dir: '/home/user/dir',
base: 'file.txt',
ext: '.txt',
name: 'file'
}
- Template by the parse method path,
ext
property to get a suffix path.
3.fs module
New a.txt file and rename.js, we are now by fs module will a.txt
rename b.txt
, we add the following code rename.js
const fs=require('fs');
fs.rename('a.txt','b.txt',function(err){
if(err){
console.log('重命名错误');
}else{
console.log('重命名成功');
}
})
Execute code, we find that a.txt
has becomeb.txt
4. Upload Photos Add Preview
The above mentioned documents we file uploaded because they do not contain a suffix, so can not be previewed, and now we pass path模块与fs模块
to achieve preview function
Change the following server.js
const express=require('express');
const multer=require('multer');
const path=require('path');
const fs=require('fs');
// const bodyParser=require('body-parser');
const server=express();
// server.use(bodyParser.urlencoded())
var objMulter=multer({dest: './uploadImages'});
server.use(objMulter.any());
server.post('/infor',function(req,res,next){
const newname=req.files[0].path+path.parse(req.files[0].originalname).ext
fs.rename(req.files[0].path,newname,function(err){
if(err){
res.send('上传失败')
}else{
res.send('上传成功')
}
})
})
server.listen(8080);
The above code should be easy to understand, acquire suffix, rename the file. Tests are as follows