nodejs和前端mysql增删改查、文件上传、文件下载、视频在线播放代码

以下是一个完整的 Node.js 实现 MySQL 数据库增删改查、前端上传文件和下载文件、前端在线播放视频的示例代码:

后端代码(app.js):

const express = require('express');
const mysql = require('mysql');
const multer = require('multer');

const app = express();
const upload = multer({ dest: 'uploads/' });

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'database_name'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL database!');
});

app.use(express.static('public'));

app.get('/api/users', (req, res) => {
  const sql = 'SELECT * FROM users';
  connection.query(sql, (err, results) => {
    if (err) throw err;
    res.json(results);
  });
});

app.post('/api/users', (req, res) => {
  const { name, email } = req.body;
  const sql = `INSERT INTO users (name, email) VALUES ('${name}', '${email}')`;
  connection.query(sql, (err, result) => {
    if (err) throw err;
    res.json({ message: 'User added successfully!', id: result.insertId });
  });
});

app.put('/api/users/:id', (req, res) => {
  const { name, email } = req.body;
  const id = req.params.id;
  const sql = `UPDATE users SET name='${name}', email='${email}' WHERE id=${id}`;
  connection.query(sql, (err, result) => {
    if (err) throw err;
    res.json({ message: 'User updated successfully!', id: id });
  });
});

app.delete('/api/users/:id', (req, res) => {
  const id = req.params.id;
  const sql = `DELETE FROM users WHERE id=${id}`;
  connection.query(sql, (err, result) => {
    if (err) throw err;
    res.json({ message: 'User deleted successfully!', id: id });
  });
});

app.post('/api/upload', upload.single('file'), (req, res) => {
  console.log(req.file);
  res.json({ message: 'File uploaded successfully!' });
});

app.get('/api/download/:filename', (req, res) => {
  const filename = req.params.filename;
  res.download(`public/${filename}`);
});

app.get('/api/video/:filename', (req, res) => {
  const filename = req.params.filename;
  res.sendFile(`public/${filename}`);
});

app.listen(3000, () => {
  console.log('Server started on port 3000!');
});

 前端代码:

<!DOCTYPE html>
<html>
<head>
  <title>Node.js MySQL File Upload and Download Example</title>
</head>
<body>
  <h1>Node.js MySQL File Upload and Download Example</h1>

  <h2>Users</h2>
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody id="users-table-body">
    </tbody>
  </table>

  <h2>Add User</h2>
  <form>
    <label for="name-input">Name:</label>
    <input type="text" id="name-input" name="name"><br><br>
    <label for="email-input">Email:</label>
    <input type="email" id="email-input" name="email"><br><br>
    <button type="submit" onclick="addUser()">Add User</button>
  </form>

  <h2>Upload File</h2>
  <form>
    <input type="file" id="file-input">
    <button type="submit" onclick="uploadFile()">Upload</button>
  </form>

  <h2>Download File</h2>
  <a href="/api/download/file.txt" download>Download</a>

  <h2>Play Video</h2>
  <video src="/api/video/video.mp4" controls></video>

  <script>
    function getUsers() {
      fetch('/api/users')
        .then(response => response.json())
        .then(data => {
          const usersTableBody = document.getElementById('users-table-body');
          usersTableBody.innerHTML = '';
          data.forEach(user => {
            const tr = document.createElement('tr');
            const idTd = document.createElement('td');
            idTd.textContent = user.id;
            const nameTd = document.createElement('td');
            nameTd.textContent = user.name;
            const emailTd = document.createElement('td');
            emailTd.textContent = user.email;
            const actionsTd = document.createElement('td');
            const editButton = document.createElement('button');
            editButton.textContent = 'Edit';
            editButton.onclick = () => editUser(user.id, user.name, user.email);
            const deleteButton = document.createElement('button');
            deleteButton.textContent = 'Delete';
            deleteButton.onclick = () => deleteUser(user.id);
            actionsTd.appendChild(editButton);
            actionsTd.appendChild(deleteButton);
            tr.appendChild(idTd);
            tr.appendChild(nameTd);
            tr.appendChild(emailTd);
            tr.appendChild(actionsTd);
            usersTableBody.appendChild(tr);
          });
        })
        .catch(error => console.error(error));
    }

    function addUser() {
      const nameInput = document.getElementById('name-input');
      const emailInput = document.getElementById('email-input');
      const name = nameInput.value;
      const email = emailInput.value;
      fetch('/api/users', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ name, email })
      })
        .then(response => response.json())
        .then(data => {
          console.log(data);
          getUsers();
        })
        .catch(error => console.error(error));
    }

    function editUser(id, name, email) {
      const newName = prompt('Enter new name:', name);
      const newEmail = prompt('Enter new email:', email);
      fetch(`/api/users/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ name: newName, email: newEmail })
      })
        .then(response => response.json())
        .then(data => {
          console.log(data);
          getUsers();
        })
        .catch(error => console.error(error));
    }

    function deleteUser(id) {
      fetch(`/api/users/${id}`, {
        method: 'DELETE'
      })
        .then(response => response.json())
        .then(data => {
          console.log(data);
          getUsers();
        })
        .catch(error => console.error(error));
    }

    function uploadFile() {
      const fileInput = document.getElementById('file-input');
      const file = fileInput.files[0];
      const formData = new FormData();
      formData.append('file', file);

      fetch('/api/upload', {
        method: 'POST',
        body: formData
      })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error(error));
    }

    getUsers();
  </script>
</body>
</html>

注意:在使用前请将 database_name 替换为您的 MySQL 数据库名称,将 password 替换为您的 MySQL 数据库密码,将 file.txt 替换为您要下载的文件名,将 video.mp4 替换为您要播放的视频文件名。另外,为了使示例代码正常工作,您需要在项目根目录下创建一个名为 public 的文件夹,并在其中添加一个名为 video.mp4 的视频文件。

猜你喜欢

转载自blog.csdn.net/m0_59799878/article/details/129545498