我的知识记录

如何修改文件上传时间 - 网页上传文件时间更改教程

在网页应用中修改文件上传时间涉及到前端和后端的协同工作。以下是一套完整的解决方案:

1. 前端实现 - 文件选择与时间设定


 
html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>文件上传时间修改工具</title> <style> .container { max-width: 600px; margin: 30px auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 8px; font-family: Arial, sans-serif; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 8px; font-weight: bold; color: #333; } input[type="file"], input[type="datetime-local"], select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; } button { background-color: #4CAF50; color: white; padding: 12px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; width: 100%; } button:hover { background-color: #45a049; } .result { margin-top: 20px; padding: 15px; border-radius: 4px; } .success { background-color: #dff0d8; color: #3c763d; border: 1px solid #d6e9c6; } .error { background-color: #f2dede; color: #a94442; border: 1px solid #ebccd1; } .info { background-color: #d9edf7; color: #31708f; border: 1px solid #bce8f1; } </style> </head> <body> <div class="container"> <h2>文件上传时间修改工具</h2> <form id="uploadForm"> <div class="form-group"> <label for="fileInput">选择文件:</label> <input type="file" id="fileInput" name="file" multiple accept="*/*" required> </div> <div class="form-group"> <label for="uploadTime">设置上传时间:</label> <input type="datetime-local" id="uploadTime" name="uploadTime"> </div> <div class="form-group"> <label for="timeZone">时区:</label> <select id="timeZone" name="timeZone"> <option value="local">本地时间</option> <option value="utc">UTC时间</option> </select> </div> <button type="submit">上传并修改时间</button> </form> <div id="result"></div> </div> <script> // 设置默认时间为当前时间 document.addEventListener('DOMContentLoaded', function() { const now = new Date(); const localDateTime = now.toISOString().slice(0, 16); document.getElementById('uploadTime').value = localDateTime; }); document.getElementById('uploadForm').addEventListener('submit', async function(e) { e.preventDefault(); const fileInput = document.getElementById('fileInput'); const uploadTime = document.getElementById('uploadTime').value; const timeZone = document.getElementById('timeZone').value; const resultDiv = document.getElementById('result'); if (!fileInput.files.length) { showResult('请选择至少一个文件', 'error'); return; } // 创建FormData对象 const formData = new FormData(); // 添加所有选中的文件 for (let i = 0; i < fileInput.files.length; i++) { formData.append('files', fileInput.files[i]); } // 添加自定义时间信息 if (uploadTime) { let timeValue; if (timeZone === 'utc') { timeValue = new Date(uploadTime + ':00Z').toISOString(); } else { timeValue = new Date(uploadTime).toISOString(); } formData.append('customUploadTime', timeValue); } try { showResult('正在上传文件...', 'info'); const response = await fetch('/api/upload', { method: 'POST', body: formData }); const result = await response.json(); if (response.ok) { showResult(`上传成功!${result.message}`, 'success'); } else { showResult(`上传失败: ${result.error}`, 'error'); } } catch (error) { showResult(`网络错误: ${error.message}`, 'error'); } }); function showResult(message, type) { const resultDiv = document.getElementById('result'); resultDiv.innerHTML = message; resultDiv.className = `result ${type}`; } </script> </body> </html>

2. 后端实现 - Node.js + Express


 
javascript
const express = require('express'); const multer = require('multer'); const path = require('path'); const fs = require('fs').promises; const app = express(); // 配置文件存储 const storage = multer.diskStorage({ destination: async function (req, file, cb) { const uploadDir = 'uploads'; try { await fs.access(uploadDir).catch(() => fs.mkdir(uploadDir)); cb(null, uploadDir); } catch (error) { cb(error, uploadDir); } }, filename: function (req, file, cb) { // 保持原始文件名,避免重复则添加时间戳 const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9); const ext = path.extname(file.originalname); const name = path.basename(file.originalname, ext); cb(null, `${name}-${uniqueSuffix}${ext}`); } }); const upload = multer({ storage: storage, limits: { fileSize: 50 * 1024 * 1024 // 50MB限制 } }); // 中间件 app.use(express.json()); app.use(express.static('public')); app.use('/uploads', express.static('uploads')); // 文件上传接口 app.post('/api/upload', upload.array('files', 10), async (req, res) => { try { const customUploadTime = req.body.customUploadTime; const uploadedFiles = req.files; if (!uploadedFiles || uploadedFiles.length === 0) { return res.status(400).json({ error: '没有文件被上传' }); } const results = []; // 处理每个上传的文件 for (const file of uploadedFiles) { const filePath = file.path; const originalName = file.originalname; // 如果提供了自定义时间,则修改文件的时间戳 if (customUploadTime) { const customTime = new Date(customUploadTime); const timestamp = customTime.getTime() / 1000; // utimes需要秒 try { await fs.utimes(filePath, timestamp, timestamp); results.push({ filename: originalName, status: 'success', customTime: customUploadTime, message: `文件时间已修改为 ${customTime.toLocaleString()}` }); } catch (error) { results.push({ filename: originalName, status: 'warning', message: `文件上传成功但时间修改失败: ${error.message}` }); } } else { results.push({ filename: originalName, status: 'success', message: '文件上传成功' }); } } res.json({ message: `成功上传 ${results.length} 个文件`, files: results }); } catch (error) { console.error('上传错误:', error); res.status(500).json({ error: '文件上传过程中发生错误', details: error.message }); } }); // 获取文件信息接口 app.get('/api/files/:filename', async (req, res) => { try { const filename = req.params.filename; const filePath = path.join('uploads', filename); const stats = await fs.stat(filePath); res.json({ filename: filename, size: stats.size, birthtime: stats.birthtime, mtime: stats.mtime, atime: stats.atime }); } catch (error) { res.status(404).json({ error: '文件未找到' }); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`服务器运行在端口 ${PORT}`); });

3. Python Flask 实现版本


 
python
from flask import Flask, request, jsonify, send_from_directory import os import json from datetime import datetime from werkzeug.utils import secure_filename import time app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads' app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 50MB max file size # 确保上传目录存在 os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) @app.route('/') def index(): return send_from_directory('public', 'index.html') @app.route('/api/upload', methods=['POST']) def upload_file(): try: # 检查是否有文件在请求中 if 'files' not in request.files: return jsonify({'error': '没有文件被上传'}), 400 files = request.files.getlist('files') custom_upload_time = request.form.get('customUploadTime') if not files or files[0].filename == '': return jsonify({'error': '没有选择文件'}), 400 results = [] for file in files: if file: filename = secure_filename(file.filename) # 为避免文件名冲突,添加时间戳 name, ext = os.path.splitext(filename) timestamp = datetime.now().strftime("%Y%m%d%H%M%S") unique_filename = f"{name}_{timestamp}{ext}" filepath = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename) file.save(filepath) # 如果提供了自定义时间,则修改文件时间戳 if custom_upload_time: try: # 解析ISO格式的时间字符串 custom_time = datetime.fromisoformat(custom_upload_time.replace('Z', '+00:00')) timestamp = custom_time.timestamp() # 修改文件的访问时间和修改时间 os.utime(filepath, (timestamp, timestamp)) results.append({ 'filename': filename, 'status': 'success', 'customTime': custom_upload_time, 'message': f'文件时间已修改为 {custom_time.strftime("%Y-%m-%d %H:%M:%S")}' }) except Exception as e: results.append({ 'filename': filename, 'status': 'warning', 'message': f'文件上传成功但时间修改失败: {str(e)}' }) else: results.append({ 'filename': filename, 'status': 'success', 'message': '文件上传成功' }) return jsonify({ 'message': f'成功上传 {len(results)} 个文件', 'files': results }) except Exception as e: return jsonify({'error': f'文件上传过程中发生错误: {str(e)}'}), 500 @app.route('/api/files/<filename>', methods=['GET']) def get_file_info(filename): try: filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) if not os.path.exists(filepath): return jsonify({'error': '文件未找到'}), 404 stat = os.stat(filepath) return jsonify({ 'filename': filename, 'size': stat.st_size, 'created': datetime.fromtimestamp(stat.st_ctime).isoformat(), 'modified': datetime.fromtimestamp(stat.st_mtime).isoformat(), 'accessed': datetime.fromtimestamp(stat.st_atime).isoformat() }) except Exception as e: return jsonify({'error': str(e)}), 500 if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=3000)

4. 使用说明

步骤1: 准备环境


 
bash
# Node.js 版本 npm install express multer # Python 版本 pip install flask

步骤2: 运行服务端


 
bash
# Node.js node server.js # Python python app.py

步骤3: 使用浏览器访问

打开浏览器访问 http://localhost:3000 即可使用文件上传时间修改功能。

5. 高级功能扩展

批量时间修改API


 
javascript
// 添加批量修改时间的接口 app.post('/api/batch-modify-time', async (req, res) => { try { const { filenames, newTime } = req.body; if (!filenames || !Array.isArray(filenames)) { return res.status(400).json({ error: '无效的文件列表' }); } if (!newTime) { return res.status(400).json({ error: '请提供新的时间' }); } const customTime = new Date(newTime); const timestamp = customTime.getTime() / 1000; const results = []; for (const filename of filenames) { try { const filePath = path.join('uploads', filename); await fs.utimes(filePath, timestamp, timestamp); results.push({ filename, status: 'success', message: '时间修改成功' }); } catch (error) { results.push({ filename, status: 'error', message: error.message }); } } res.json({ message: `处理完成,成功修改 ${results.filter(r => r.status === 'success').length} 个文件`, results }); } catch (error) { res.status(500).json({ error: error.message }); } });
这套完整的解决方案允许用户通过网页界面上传文件并自定义文件的时间戳,适用于各种需要控制文件时间属性的应用场景。
 

如何修改文件上传时间 - 网页上传文件时间更改教程

标签:

更新时间:2025-12-13 18:07:58

上一篇:文件上传时间修改全攻略 - 适用于各类网页平台

下一篇:网上上传文件如何更改上传时间 - 完整操作指南