求基于http.server/Node.js的浏览器文件上传-Python处理-前端下载基础方法
基础实现方案:浏览器文件上传→Python处理→返回下载
这里提供两种最基础的实现方案,分别基于Python的http.server和Node.js + Express,完全覆盖你需要的流程:
方案一:使用Python http.server实现
目录结构
先搭好基础目录,每个文件各司其职:
project/ ├── server.py # HTTP服务端脚本 ├── process_file.py # 文件处理核心脚本 ├── upload.html # 前端上传表单页面 ├── temp/ # 临时存储上传/生成文件(需手动创建)
1. 前端上传表单(upload.html)
简单的HTML表单,支持文件上传提交:
<!DOCTYPE html> <html> <head> <title>文件上传处理</title> </head> <body> <h3>上传文件进行处理</h3> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file" accept=".txt"> <button type="submit">上传并处理</button> </form> </body> </html>
2. 文件处理脚本(process_file.py)
这里做个示例逻辑:读取上传的文本文件,转成大写后生成新文件,你可以替换成自己的处理逻辑:
import sys def process(input_path, output_path): with open(input_path, 'r', encoding='utf-8') as f: content = f.read() # 替换成你的实际文件处理逻辑 processed_content = content.upper() with open(output_path, 'w', encoding='utf-8') as f: f.write(processed_content) if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: python process_file.py <input_file> <output_file>") sys.exit(1) input_file = sys.argv[1] output_file = sys.argv[2] process(input_file, output_file)
3. HTTP服务端脚本(server.py)
继承BaseHTTPRequestHandler,处理GET请求返回表单、POST请求处理上传/调用脚本/返回下载:
import os import sys import cgi import subprocess from http.server import HTTPServer, BaseHTTPRequestHandler # 基础配置 UPLOAD_DIR = './temp' PROCESS_SCRIPT = './process_file.py' PORT = 8000 class FileHandler(BaseHTTPRequestHandler): def do_GET(self): # 根路径返回上传表单 if self.path == '/': self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() with open('upload.html', 'rb') as f: self.wfile.write(f.read()) else: self.send_error(404, "Page not found") def do_POST(self): if self.path == '/upload': # 解析上传的表单数据 form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type']} ) file_item = form.getvalue('uploaded_file') if not file_item: self.send_error(400, "No file uploaded") return # 保存上传文件到临时目录 filename = os.path.basename(file_item.filename) input_path = os.path.join(UPLOAD_DIR, filename) with open(input_path, 'wb') as f: f.write(file_item.file.read()) # 调用Python处理脚本生成新文件 output_filename = f"processed_{filename}" output_path = os.path.join(UPLOAD_DIR, output_filename) try: subprocess.run([sys.executable, PROCESS_SCRIPT, input_path, output_path], check=True) except subprocess.CalledProcessError as e: self.send_error(500, f"Processing failed: {str(e)}") return # 返回生成的文件供下载 self.send_response(200) self.send_header('Content-Type', 'application/octet-stream') self.send_header('Content-Disposition', f'attachment; filename="{output_filename}"') self.end_headers() with open(output_path, 'rb') as f: self.wfile.write(f.read()) # 可选:清理临时文件 os.remove(input_path) os.remove(output_path) if __name__ == '__main__': # 确保临时目录存在 if not os.path.exists(UPLOAD_DIR): os.makedirs(UPLOAD_DIR) server = HTTPServer(('', PORT), FileHandler) print(f"Server running on port {PORT}, visit http://localhost:{PORT}") try: server.serve_forever() except KeyboardInterrupt: server.server_close() print("\nServer stopped.")
运行方式
- 创建
temp文件夹 - 执行
python server.py启动服务 - 浏览器访问
http://localhost:8000,上传txt文件即可下载处理后的文件
方案二:使用Node.js + Express实现
初始化项目
先创建项目并安装依赖:
mkdir node-file-process cd node-file-process npm init -y npm install express multer
目录结构
node-file-process/ ├── app.js # 服务端主脚本 ├── process_file.py # 和Python方案复用的处理脚本 ├── upload.html # 和Python方案复用的上传表单 ├── temp/ # 临时文件夹(需手动创建)
服务端脚本(app.js)
用multer处理文件上传,child_process调用Python脚本:
const express = require('express'); const multer = require('multer'); const { execFile } = require('child_process'); const fs = require('fs'); const path = require('path'); const app = express(); const PORT = 3000; const UPLOAD_DIR = './temp'; // 配置multer存储上传文件 const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, UPLOAD_DIR); }, filename: (req, file, cb) => { cb(null, file.originalname); } }); const upload = multer({ storage: storage }); // 返回上传表单 app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'upload.html')); }); // 处理文件上传和后续流程 app.post('/upload', upload.single('uploaded_file'), (req, res) => { if (!req.file) { return res.status(400).send('No file uploaded'); } const inputPath = req.file.path; const outputFilename = `processed_${req.file.originalname}`; const outputPath = path.join(UPLOAD_DIR, outputFilename); // 调用Python处理脚本 execFile('python', ['./process_file.py', inputPath, outputPath], (error, stdout, stderr) => { if (error) { console.error(`Processing error: ${error.message}`); return res.status(500).send('File processing failed'); } if (stderr) { console.error(`Script stderr: ${stderr}`); return res.status(500).send('Script execution error'); } // 返回生成的文件供下载 res.download(outputPath, outputFilename, (err) => { // 清理临时文件 fs.unlink(inputPath, () => {}); fs.unlink(outputPath, () => {}); if (err) { res.status(500).send('Failed to download file'); } }); }); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
运行方式
- 创建
temp文件夹 - 执行
node app.js启动服务 - 浏览器访问
http://localhost:3000,上传txt文件后即可下载处理后的文件
内容的提问来源于stack exchange,提问作者Tissa K
相关产品推荐
相关产品推荐

