1. 程式人生 > 其它 >使用node上傳檔案到資料夾

使用node上傳檔案到資料夾

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>

這是我的目錄結構: