需求
在當(dāng)今數(shù)字化時(shí)代,文件上傳需求日益普遍。無(wú)論是個(gè)人還是企業(yè),都可能需要實(shí)現(xiàn)文件上傳功能。為此,本文將分享如何使用Python Flask框架創(chuàng)建一個(gè)簡(jiǎn)易的Web端上傳文件程序。
介紹
需要源碼的留下郵箱,私信也會(huì)看,不過(guò)看的不勤,留言有通知。
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-852847.html
Flask 是一個(gè)用于構(gòu)建 Web 應(yīng)用程序的輕量級(jí) Python Web 框架。它設(shè)計(jì)簡(jiǎn)單、易于學(xué)習(xí)和使用,但同時(shí)也非常靈活,適用于從小型項(xiàng)目到大型應(yīng)用程序的各種場(chǎng)景。
核心代碼:
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return '無(wú)文件部分'
file = request.files['file']
if file.filename == '':
return '沒(méi)有可選擇的文件'
if file:
# 設(shè)置文件存儲(chǔ)路徑
upload_path = os.path.join('static/uploads', file.filename)
# 檢測(cè)路徑是否存在,不存在則創(chuàng)建
if not os.path.exists(os.path.dirname(upload_path)):
os.makedirs(os.path.dirname(upload_path))
# 存儲(chǔ)文件
file.save(upload_path)
return '文件已上傳'
在Flask中,request.files
是用于處理上傳文件的對(duì)象。當(dāng)用戶通過(guò)表單上傳文件時(shí),這個(gè)對(duì)象可以用來(lái)訪問(wèn)和處理上傳的文件數(shù)據(jù)。request.files
是一個(gè)字典,其中鍵是表單中文件上傳字段的名稱,值是與該字段相關(guān)聯(lián)的文件對(duì)象。
request.files
字典中文件對(duì)象常見的字段和方法:
字段/方法 | 描述 | 示例 |
---|---|---|
filename |
獲取上傳文件的原始文件名 | filename = request.files[‘file’].filename |
stream |
獲取文件的二進(jìn)制流,可用于讀取文件內(nèi)容 | file_content = request.files[‘file’].stream.read() |
content_type |
獲取文件的MIME類型。 | content_type = request.files[‘file’].content_type |
content_length |
獲取文件的內(nèi)容長(zhǎng)度(以字節(jié)為單位) | content_length = request.files[‘file’].content_length |
save(destination) |
將上傳的文件保存到指定的目標(biāo)路徑destination 是保存文件的路徑,可以是相對(duì)路徑或絕對(duì)路徑 |
request.files[‘file’].save(‘uploads/’ + filename) |
file.save()
是用于將上傳的文件保存到指定的目標(biāo)路徑。
文件結(jié)構(gòu)
下面我們介紹一下我們的文件結(jié)構(gòu)
前端文件
templates.index.html
后端文件
main.py
完整代碼
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件工作臺(tái)</title>
</head>
<body>
<h1>文件工作臺(tái)</h1>
<form>
<input type="file" id="file" name="file">
<button type="button" onclick="uploadFile()">上傳文件</button>
</form>
</body>
</html>
<script>
function uploadFile() {
var fileInput = document.getElementById('file');
var file = fileInput.files[0];
if (file) {
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.onload = function () {
if (xhr.status == 200) {
alert('文件上傳成功');
} else {
alert('文件上傳失敗');
}
};
xhr.send(formData);
} else {
alert('請(qǐng)選擇一個(gè)文件');
}
}
</script>
main.py
import os
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return '無(wú)文件部分'
file = request.files['file']
if file.filename == '':
return '沒(méi)有可選擇的文件'
if file:
# 設(shè)置文件存儲(chǔ)路徑
upload_path = os.path.join('static/uploads', file.filename)
# 檢測(cè)路徑是否存在,不存在則創(chuàng)建
if not os.path.exists(os.path.dirname(upload_path)):
os.makedirs(os.path.dirname(upload_path))
# 存儲(chǔ)文件
file.save(upload_path)
return '文件已上傳'
if __name__ == '__main__':
app.run()
演示
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-852847.html
需要源碼的留下郵箱,私信也會(huì)看,不過(guò)看的不勤,留言有通知。
到了這里,關(guān)于python Flask 寫一個(gè)簡(jiǎn)易的 web 端上傳文件程序 (附demo)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!