使用Python快速搭建简易Web方便iPad和PC互传文件
使用 iPad 和 PC 电脑互传文件太麻烦了,要么两边都装上微信互传文件,这样重复的文件越来越多。干脆建立一个简单的 Web 服务器,这样两边上传下载文件方便多了。
先创建一个uploads目录,然后安装 flask 框架,最后创建一个 app.py 文件,代码如下
from flask import Flask, request, send_from_directory
import os
app = Flask(__name__)
# Set upload folder
UPLOAD_FOLDER = './uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/')
def index():
files_list = "\n".join(
f'<li><a href="/download/{file}">{file}</a></li>'
for file in os.listdir(UPLOAD_FOLDER)
)
return f'''
<!doctype html>
<title>File Upload with Progress</title>
<h1>Upload File with Progress</h1>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" id="fileInput">
<button type="button" onclick="uploadFile()">Upload</button>
</form>
<br>
<progress id="progressBar" value="0" max="100" style="width: 100%;"></progress>
<br><br>
<div id="status"></div>
<h1>Download Files</h1>
<ul>
{files_list}
</ul>
<script>
function uploadFile() {{
const fileInput = document.getElementById('fileInput');
const progressBar = document.getElementById('progressBar');
const status = document.getElementById('status');
if (!fileInput.files.length) {{
status.innerHTML = "Please select a file.";
return;
}}
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.upload.onprogress = function(event) {{
if (event.lengthComputable) {{
const percentComplete = (event.loaded / event.total) * 100;
progressBar.value = percentComplete;
}}
}};
xhr.onload = function() {{
if (xhr.status === 200) {{
status.innerHTML = "File uploaded successfully. <a href='/'>Refresh to view files</a>";
progressBar.value = 0;
}} else {{
status.innerHTML = "Error uploading file.";
}}
}};
xhr.onerror = function() {{
status.innerHTML = "Upload failed. Please try again.";
}};
xhr.send(formData);
}}
</script>
'''
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return 'No file part', 400
file = request.files['file']
if file.filename == '':
return 'No selected file', 400
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
return 'File uploaded successfully', 200
@app.route('/download/<filename>')
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
最后运行 python app.py,然后就会在 5000 端口上创建一个 Web 服务。
评论已关闭