前端

    1. <script>
    2. let file = null;
    3. document.getElementById('file').addEventListener('change', (e) => {
    4. file = e.target.files[0];
    5. })
    6. function updateFile() {
    7. if (file === null) return;
    8. const formData = new FormData();
    9. formData.append('file', file);
    10. axios({
    11. url: "http://localhost:3000/file",
    12. method: "POST",
    13. data: formData
    14. })
    15. .then(res => console.log(res))
    16. .catch(err => console.log(err))
    17. }
    18. </script>

    后端

    const express = require('express');
    const app = express();
    const fs = require('fs');
    const multer = require('multer');
    const path = require('path');
    const DIR_PATH = path.join(__dirname, 'upload');
    const upload = multer({ dest: DIR_PATH }) //  文件存放的地方
    
    app.use(express.static(path.join(__dirname, 'public')))
    app.get('/', (req, res) => {
        res.send('123')
    })
    
    app.post('/file', upload.single('file'), (req, res) => {
        const oldFilePath = req.file.path;
        const newFilePath = path.join(DIR_PATH, req.file.originalname);
        fs.rename(oldFilePath, newFilePath, (err) => {
            if (err) return console.log(err);
            res.send('ok')
        })
    })
    app.listen(3000, () => console.log(3000))