创建express项目,实现上传多文件


前言

创建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文件夹里面已经有文件了,表示上传成功

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

leewen5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值