文章目录
前言
创建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、安装multer库
上传图片需要multer库,安装,查看文档
npm install --save multer
完整的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",
"multer": "^1.4.2"
}
}
2、修改index.js文件
在myapp根目录创建uploads文件夹。
上传文件使用post发送,app.get修改为app.post
const express = require('express')
const app = express()
var multer = require('multer') // 引入multer库
var upload = multer({ dest: 'uploads/' }) // 配置上传存放目录
const port = 3000
// upload.single('avatar') avatar是file的名称
app.post('/', upload.single('avatar'), function (req, res, next) {
console.log(req.file); //在vscode控制台打印文件信息
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}`)
})
修改了文件必须要保存,然后重新执行启动项目命令
3、修改postman信息
如图,注意红框选择
vscode也打印出了file信息,uploads文件夹里面已经有文件了,表示上传成功
4、修改上传的文件名称
现在上传的是按照multer默认上传的方式,文件是打不开的,我们需要进行配置
5、修改后的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.single('avatar'), function (req, res, next) {
console.log(req.file);
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}`)
})
保存文件,重新启动项目,再到postman测试
上传成功了,文件也正常