How to use MySQL and JavaScript to implement a simple file browsing function
Introduction:
In today's digital age, file management and browsing functions have become part of our daily work Indispensable part. This article will introduce how to use MySQL and JavaScript to implement a simple file browsing function. We will use MySQL as the database to store the file's metadata and JavaScript to implement the user interface and file operations.
CREATE TABLE files (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
size INT,
path VARCHAR (255)
);
const fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', (event) => { const selectedFile = event.target.files[0]; const xhr = new XMLHttpRequest(); xhr.open('POST', '/upload'); xhr.send(selectedFile); });
const express = require('express'); const mysql = require('mysql'); const app = express(); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'files' }); app.get('/files', (req, res) => { connection.query('SELECT * FROM files', (error, results) => { if (error) throw error; res.json(results); }); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
fetch('/files') .then(response => response.json()) .then(data => { const fileList = document.getElementById('fileList'); data.forEach(file => { const listItem = document.createElement('li'); listItem.textContent = file.name; fileList.appendChild(listItem); }); });
Through the above steps, we can implement a simple file browsing function. Users can upload files and see a list of uploaded files in the interface. Of course, this is just a basic example. We can expand and optimize this function according to our own needs, such as adding file deletion and download functions.
Conclusion:
A simple file browsing function can be easily implemented using MySQL and JavaScript. By storing file metadata in MySQL and using JavaScript to control file upload, query, and display, we can quickly build a file management and browsing interface. Of course, based on actual needs, we can further expand and optimize this function and add more file operation functions.
The above is the detailed content of How to use MySQL and JavaScript to implement a simple file browsing function. For more information, please follow other related articles on the PHP Chinese website!