使用Python快速搭建文件傳輸服務的方法
當我的朋友需要把他電腦上面的文件從他的電腦傳遞到我電腦上的時候,我只需要啟動服務
啟動服務!

他打開web界面

就能把文件傳遞到我電腦上(還能夠實時顯示進度)

文件就已經在我電腦上的uploads文件夾里面了

項目結構如下
templates 存放前端html文件
? updoad.html 上傳文件的界面
uploads 存放用戶上傳的文件
? 保研準備資料.zip 剛剛上傳的文件
upload.py 后端服務文件

當你和朋友在同一個局域網內,當然可以直接根據主機的ip遠程傳輸。當你們兩個不在同一個網絡內的時候,可以用frp內網穿透將一臺主機的ip變成公網ip,也能實時進行傳輸了。
優(yōu)點:
- 簡單快速,不需要打開qq,微信等軟件傳輸
- 沒有文件大小限制
- 進度實時顯示
- 局域網也不需要聯網,也非??焖?,
后端服務搭建
用flask來搭建web服務
from flask import Flask, render_template, request, jsonify
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads' # 上傳文件保存的目錄
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/')
def index():
return render_template('upload.html')
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
if file:
filename = file.filename
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
return '文件上傳成功!'
@app.route('/progress', methods=['POST'])
def progress():
uploaded_bytes = request.form['uploadedBytes']
total_bytes = request.form['totalBytes']
progress = int(uploaded_bytes) / int(total_bytes) * 100
return jsonify(progress=progress)
if __name__ == '__main__':
app.run(debug=True)只需要定義三個接口
- / : 默認訪問html頁面,來供用戶操作
- /upload :上傳文件的post接口
- /progress : 實時顯示進度的post接口
前臺頁面撰寫
<!doctype html>
<html>
<head>
<title>文件上傳</title>
<script>
function uploadFile() {
var fileInput = document.getElementById('file');
var file = fileInput.files[0];
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var progress = Math.round((event.loaded / event.total) * 100);
document.getElementById('progress').innerText = progress + '%';
}
};
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('progress').innerText = '上傳完成';
}
};
var formData = new FormData();
formData.append('file', file);
xhr.send(formData);
}
function updateProgress() {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/progress');
xhr.onload = function() {
if (xhr.status === 200) {
var progress = JSON.parse(xhr.responseText).progress;
document.getElementById('progress').innerText = progress + '%';
}
};
xhr.send();
}
setInterval(updateProgress, 1000); // 每秒更新一次進度
</script>
</head>
<body>
<h1>文件上傳</h1>
<input type="file" id="file">
<button onclick="uploadFile()">上傳</button>
<div id="progress"></div>
</body>
</html>只需要執(zhí)行兩個函數就行
- onload() : 文件上傳函數,調用后臺的 upload 上傳文件接口
- updateProgress() : 定時訪問后臺顯示進度的 progress 接口,來獲取文件上傳的進度,進度計算后展示百分比給用戶
這樣任何一個人都能打開瀏覽器把他電腦上的文件傳給我了。
到此這篇關于使用Python快速搭建一個文件傳輸服務的文章就介紹到這了,更多相關Python搭建文件傳輸服務內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python創(chuàng)建屬于自己的單詞詞庫 便于背單詞
這篇文章主要為大家詳細介紹了python創(chuàng)建屬于自己的單詞詞庫,便于背單詞,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07
Pytorch對Himmelblau函數的優(yōu)化詳解
今天小編就為大家分享一篇Pytorch對Himmelblau函數的優(yōu)化詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02

