我的知识记录

修改服务器上传文件时间(图文)

修改服务器上传文件时间有多种方法,以下是针对不同场景的详细解决方案:

1. 上传前修改文件时间(客户端)

使用命令行工具

Linux/macOS:


 
bash
# 修改文件时间后再上传 touch -m -t 202312251430 filename.txt scp filename.txt user@server:/path/to/upload/

Windows PowerShell:


 
powershell
# 修改文件时间 (Get-Item "filename.txt").LastWriteTime = "2023-12-25 14:30:00" # 上传文件(使用SCP、FTP等工具)

编程方式准备文件

Python脚本:


 
python
import os import time import paramiko # 用于SSH连接 def prepare_and_upload_file(local_file, remote_path, timestamp): """ 修改文件时间并上传到服务器 """ # 1. 修改本地文件时间 os.utime(local_file, (timestamp, timestamp)) # 2. 上传文件到服务器 ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('your-server.com', username='username', password='password') sftp = ssh.open_sftp() sftp.put(local_file, remote_path) sftp.close() ssh.close() # 使用示例 timestamp = time.mktime((2023, 12, 25, 14, 30, 0, 0, 0, 0)) prepare_and_upload_file('document.txt', '/remote/path/document.txt', timestamp)

2. 服务器端修改已上传文件时间

SSH登录服务器后修改

Linux服务器:


 
bash
# 登录服务器后修改文件时间 ssh user@server.com cd /path/to/uploaded/files touch -m -t 202312251430 uploaded_file.txt

使用脚本批量处理:


 
bash
#!/bin/bash # 批量修改服务器上文件的时间 ssh user@server.com << 'EOF' cd /path/to/uploaded/files for file in *.txt; do touch -m -t 202312251430 "$file" done EOF

Python远程执行:


 
python
import paramiko def modify_remote_file_time(hostname, username, password, filepath, new_time): """ 远程修改服务器文件时间 """ ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(hostname, username=username, password=password) # 执行修改时间的命令 command = f'touch -m -t {new_time} {filepath}' stdin, stdout, stderr = ssh.exec_command(command) # 检查执行结果 error = stderr.read().decode() if error: print(f"错误: {error}") else: print(f"成功修改文件 {filepath} 的时间") finally: ssh.close() # 使用示例 modify_remote_file_time( 'your-server.com', 'username', 'password', '/path/to/file.txt', '202312251430' )

3. Web上传接口中处理时间

后端接收并设置自定义时间

Node.js Express示例:


 
javascript
const express = require('express'); const multer = require('multer'); const fs = require('fs'); const path = require('path'); const app = express(); // 配置文件存储 const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/') }, filename: function (req, file, cb) { // 使用原始文件名或生成唯一名称 cb(null, Date.now() + '-' + file.originalname) } }); const upload = multer({ storage: storage }); app.post('/upload', upload.single('file'), (req, res) => { if (!req.file) { return res.status(400).json({ error: '没有上传文件' }); } // 获取客户端发送的自定义时间 let customTime = req.body.upload_time; if (customTime) { // 转换为时间戳 const timestamp = new Date(customTime).getTime() / 1000; // 修改文件时间 fs.utimes(req.file.path, timestamp, timestamp, (err) => { if (err) { console.error('修改文件时间失败:', err); return res.status(500).json({ error: '文件处理失败' }); } res.json({ message: '文件上传成功,时间已设置', filename: req.file.filename, upload_time: customTime }); }); } else { // 使用当前时间 res.json({ message: '文件上传成功', filename: req.file.filename }); } }); app.listen(3000);

Python Flask示例:


 
python
from flask import Flask, request, jsonify import os import time from datetime import datetime from werkzeug.utils import secure_filename app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads' @app.route('/upload', methods=['POST']) def upload_file(): if 'file' not in request.files: return jsonify({'error': '没有文件'}), 400 file = request.files['file'] if file.filename == '': return jsonify({'error': '未选择文件'}), 400 # 保存文件 filename = secure_filename(file.filename) filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(filepath) # 获取自定义时间参数 custom_time = request.form.get('upload_time') if custom_time: try: # 解析时间字符串 dt = datetime.fromisoformat(custom_time) timestamp = dt.timestamp() # 修改文件时间 os.utime(filepath, (timestamp, timestamp)) return jsonify({ 'message': '文件上传成功,时间已设置', 'filename': filename, 'upload_time': custom_time }) except ValueError: return jsonify({'error': '时间格式错误'}), 400 else: return jsonify({ 'message': '文件上传成功', 'filename': filename }) if __name__ == '__main__': app.run(debug=True)

4. FTP/SFTP上传时处理

Python FTP示例:


 
python
import ftplib import os import time def upload_with_custom_time(ftp_host, ftp_user, ftp_pass, local_file, remote_file, custom_time): """ 上传文件并设置自定义时间 """ # 1. 先修改本地文件时间 os.utime(local_file, (custom_time, custom_time)) # 2. 上传文件 ftp = ftplib.FTP(ftp_host) ftp.login(ftp_user, ftp_pass) with open(local_file, 'rb') as file: ftp.storbinary(f'STOR {remote_file}', file) ftp.quit() print(f"文件 {local_file} 已上传到 {remote_file}") # 使用示例 timestamp = time.mktime((2023, 12, 25, 14, 30, 0, 0, 0, 0)) upload_with_custom_time( 'ftp.server.com', 'username', 'password', 'local_file.txt', 'remote_file.txt', timestamp )

5. 使用Ansible自动化处理


 
yaml
--- - name: 修改服务器文件时间 hosts: webservers tasks: - name: 修改文件时间戳 file: path: /var/www/uploads/{{ item }} modification_time: "2023-12-25 14:30:00" access_time: "2023-12-25 14:30:00" loop: - file1.txt - file2.txt - file3.txt - name: 批量修改目录下所有文件时间 shell: find /var/www/uploads -type f -exec touch -m -t 202312251430 {} \;

6. 数据库记录上传时间

SQL表结构:


 
sql
CREATE TABLE uploaded_files ( id INT PRIMARY KEY AUTO_INCREMENT, filename VARCHAR(255) NOT NULL, filepath VARCHAR(500) NOT NULL, actual_upload_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, custom_upload_time DATETIME NULL, user_id INT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- 插入记录时设置自定义时间 INSERT INTO uploaded_files (filename, filepath, custom_upload_time, user_id) VALUES ('document.txt', '/uploads/document.txt', '2023-12-25 14:30:00', 123);

7. 完整的上传处理流程


 
python
import os import time import hashlib from datetime import datetime class FileUploader: def __init__(self, upload_dir): self.upload_dir = upload_dir os.makedirs(upload_dir, exist_ok=True) def upload_file(self, file_content, original_filename, custom_time=None): """ 上传文件并设置时间 """ # 生成唯一文件名 timestamp = str(int(time.time())) file_hash = hashlib.md5(file_content).hexdigest()[:8] new_filename = f"{timestamp}_{file_hash}_{original_filename}" filepath = os.path.join(self.upload_dir, new_filename) # 保存文件 with open(filepath, 'wb') as f: f.write(file_content) # 设置文件时间 if custom_time: if isinstance(custom_time, str): dt = datetime.fromisoformat(custom_time) timestamp_value = dt.timestamp() else: timestamp_value = custom_time os.utime(filepath, (timestamp_value, timestamp_value)) return { 'filename': new_filename, 'filepath': filepath, 'upload_time': custom_time or datetime.now().isoformat() } # 使用示例 uploader = FileUploader('/var/www/uploads') with open('document.txt', 'rb') as f: content = f.read() result = uploader.upload_file( content, 'document.txt', '2023-12-25T14:30:00' ) print(result)

注意事项

  1. 权限管理: 确保有足够的权限修改服务器文件时间
  2. 安全性: 验证用户输入的时间参数,防止恶意操作
  3. 审计跟踪: 记录实际上传时间和用户设置的时间
  4. 备份策略: 修改重要文件时间前做好备份
  5. 合规性: 确保修改行为符合业务和法律要求
选择哪种方法取决于你的具体需求:
  • 如果是个人使用,直接SSH登录修改最快捷
  • 如果是自动化流程,建议使用编程方式处理
  • 如果是Web应用,应该在上传接口中处理时间设置

修改服务器上传文件时间(图文)

标签:

更新时间:2025-12-15 14:30:21

上一篇:如何修改文件属性时间(图文)

下一篇:word文档创建时间怎么修改(图文)