首页 > 编程语言 >使用node上传文件到文件夹

使用node上传文件到文件夹

时间:2022-12-02 16:12:04浏览次数:57  
标签:node const app express upload 文件夹 multer file 上传

1、安装multer和path:

npm install multer multer -s

Or

yarn add multer multer -s

2、新建upload.js:

// 1.引入
const express = require('express');
const multer = require('multer');
const path = require('path');

// 创建router
const router = express.Router();

// 设置保存路径和文件名
const storage = multer.diskStorage({
  destination: function (req, res, cb) {
    // 设置文件存储路径
    cb(null, './file');
  },
  filename: function (req, file, cb) {
    // 设置文件名(可以自己定义)
    let fileData = Date.now() + '-' + Math.round(Math.random() * 1e9) + path.extname(file.originalname);
    cb(null, file.fieldname + '-' + fileData);
  }
});
const upload = multer({
  storage
});

// 单个文件上传
router.post('/upload/single', upload.single('file'), (req, res) => {
  res.json({
    code: 200,
    msg: '上传成功!',
    data: req.file
  });
});

// 多个文件上传
router.post('/upload/array', upload.array('file'), (req, res) => {
  res.json({
    code: 200,
    msg: '上传成功!',
    data: req.file
  });
});

// 导出router
module.exports = router;

3、引入:

//1.引入express模块
const express = require('express');
const mongoose = require('mongoose');
const bodyParse = require('body-parser');
const app = express();
mongoose
  .connect('mongodb://127.0.0.1:27017/admin', {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => console.log('数据库连接成功!'))
  .catch((err) => console.log(err));

//创建app对象
app.use(bodyParse.json());
app.use(bodyParse.urlencoded({ extended: true }));

// 定义服务启动接口
app.listen(3000, () => {
  console.log('app 3000');
});

//引入刚才定义的upload路由并应用
const Upload = require('./routes/upload');
app.use('/api', Upload);

4、使用(这里以Element-plus为例):

<template>
  <el-upload
    v-model:file-list="fileList"
    action="/api/upload/single"
    :multiple=“false”
  >
    <el-button type="primary">上传文件</el-button>
    <template #tip>
      <div class="el-upload__tip">文件不能大于500kb</div>
    </template>
  </el-upload>
</template>

<script setup>
import { ref } from 'vue';
const fileList = ref([]);
</script>

这是我的目录结构:

 

 

 

标签:node,const,app,express,upload,文件夹,multer,file,上传
From: https://www.cnblogs.com/zaijin-yang/p/16944754.html

相关文章