如何使用JavaScript实现.woff字体文件上传至指定目录并将文件名存入变量以修改网站全局字体
Great question! Let's break this down into two clear parts to solve your font upload and dynamic styling needs:
1. Implementing File Upload to public/fonts/
To upload a .woff file to your server's specified directory, you'll need both frontend code (to let users select files) and backend code (to handle storing the file). Below's a practical example using HTML/JavaScript (frontend) and Node.js/Express (backend)—adjust the backend part if you're using a different stack like PHP, Python, etc.
Frontend Code
First, add a file input and submit button to your HTML:
<input type="file" id="fontUpload" accept=".woff" /> <button onclick="uploadFont()">Upload Font</button>
Then add the JavaScript to handle the upload request:
async function uploadFont() { const fileInput = document.getElementById('fontUpload'); const file = fileInput.files[0]; if (!file || file.type !== 'font/woff') { alert('Please select a valid .woff font file!'); return; } const formData = new FormData(); formData.append('fontFile', file); try { const response = await fetch('/upload-font', { method: 'POST', body: formData }); if (response.ok) { const result = await response.json(); // Pass the filename to our font styling function setGlobalFont(result.filename); alert('Font uploaded successfully!'); } else { alert('Upload failed. Please try again.'); } } catch (error) { console.error('Upload error:', error); alert('An error occurred during upload.'); } }
Backend Code (Node.js/Express)
First, install required packages:
npm install express multer
Then set up the server with multer (a middleware for handling file uploads):
const express = require('express'); const multer = require('multer'); const path = require('path'); const app = express(); // Configure multer to store files in public/fonts/ const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, path.join(__dirname, 'public/fonts/')); }, filename: function (req, file, cb) { // Keep the original filename as you requested cb(null, file.originalname); // Optional: Add a timestamp to avoid filename conflicts // cb(null, Date.now() + '-' + file.originalname); } }); const upload = multer({ storage: storage, fileFilter: function (req, file, cb) { // Restrict to only .woff files if (file.mimetype === 'font/woff') { cb(null, true); } else { cb(new Error('Only .woff files are allowed!'), false); } } }); // Handle the upload endpoint app.post('/upload-font', upload.single('fontFile'), (req, res) => { if (!req.file) { return res.status(400).json({ error: 'No file uploaded' }); } // Send the original filename back to the frontend res.json({ filename: req.file.originalname }); }); // Serve static files from the public directory app.use(express.static('public')); app.listen(3000, () => { console.log('Server running on port 3000'); });
2. Store Filename & Modify Global CSS
Once the upload succeeds and you have the filename, you can dynamically inject a @font-face rule into your page and update the global font family. Add this function to your frontend JavaScript:
function setGlobalFont(fontFilename) { // Create a new style element const style = document.createElement('style'); // Define the @font-face rule using the uploaded filename const fontFaceRule = ` @font-face { font-family: 'UploadedFont'; src: url('/fonts/${fontFilename}') format('woff'); font-weight: normal; font-style: normal; } `; // Apply the new font to all elements style.textContent = fontFaceRule + 'body, * { font-family: \'UploadedFont\', sans-serif !important; }'; // Append the style to the head (overrides existing font styles) document.head.appendChild(style); }
Key Notes:
- Filename Conflicts: If multiple users upload files with the same name, the older file will be overwritten. To prevent this, modify the backend's
filenamefunction to add a unique identifier (like a timestamp or user ID) to the filename. - Fallback Fonts: Always include a fallback font (like
sans-serif) in thefont-familyrule to ensure readability if the uploaded font fails to load. - Browser Support:
.woffis widely supported across modern browsers, but you can add additional font formats (like.woff2) later if needed.
内容的提问来源于stack exchange,提问作者Guuunchev

