文章目录
前言
创建express项目实现上传文件
提示:以下是本篇文章正文内容,下面案例可供参考
一、搭建express项目
1、创建文件夹
创建express步骤可以参考官方网站
mkdir myapp
2、初始化 package.json 文件
通过 以下 命令为你的应用创建一个 package.json 文件
npm init
3、安装express
npm install --save express
4、创建index.js入口文件
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
保存index.js,然后在package.json里面scripts加如下代码作为启动项目:
"dev": "node index.js"
package.json文件代码如下:
{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "node index.js" // 这是加入的代码
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
5、启动项目
运行命令
npm run dev
看到Example app listening at http://localhost:3000 表示启动成功,访问地址:http://localhost:3000
6、打开postman访问地址是否成功
输入地址:http://localhost:3000,请求方式:GET,点击:send按钮,下面body内容就会显示“Hello World”,表示项目访问成功
二、实现上传多图片
1、修改index.js文件
const express = require('express')
const app = express()
var multer = require('multer')
let upload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) { // 存放路径
cb(null, './uploads/');
},
filename: function (req, file, cb) { // 修改文件名称
var changedName = (new Date().getTime())+'-'+file.originalname;
cb(null, changedName);
}
})
});
const port = 3000
app.post('/', upload.array('avatar', 3), function (req, res, next) {
console.log(req.files);
res.json("上传成功");
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
2、使用postman上传
3、上传成功
vscode打印出了files信息,uploads文件夹里面已经有文件了,表示上传成功