Flask Web開(kāi)發(fā)入門之文件上傳(八)
本章我們介紹Flask Web開(kāi)發(fā)中涉及的文件上傳模塊
定義后臺(tái)接收處理邏輯
# http://flask.pocoo.org/docs/0.12/patterns/fileuploads/
@app.route('/upload', methods=['POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
logger.debug('No file part')
return jsonify({'code': -1, 'filename': '', 'msg': 'No file part'})
file = request.files['file']
# if user does not select file, browser also submit a empty part without filename
if file.filename == '':
logger.debug('No selected file')
return jsonify({'code': -1, 'filename': '', 'msg': 'No selected file'})
else:
try:
if file and allowed_file(file.filename):
origin_file_name = file.filename
logger.debug('filename is %s' % origin_file_name)
# filename = secure_filename(file.filename)
filename = origin_file_name
if os.path.exists(UPLOAD_PATH):
logger.debug('%s path exist' % UPLOAD_PATH)
pass
else:
logger.debug('%s path not exist, do make dir' % UPLOAD_PATH)
os.makedirs(UPLOAD_PATH)
file.save(os.path.join(UPLOAD_PATH, filename))
logger.debug('%s save successfully' % filename)
return jsonify({'code': 0, 'filename': origin_file_name, 'msg': ''})
else:
logger.debug('%s not allowed' % file.filename)
return jsonify({'code': -1, 'filename': '', 'msg': 'File not allowed'})
except Exception as e:
logger.debug('upload file exception: %s' % e)
return jsonify({'code': -1, 'filename': '', 'msg': 'Error occurred'})
else:
return jsonify({'code': -1, 'filename': '', 'msg': 'Method not allowed'})
判定文件類型
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
前臺(tái)頁(yè)面代碼
<div class="layui-inline">
<label class="layui-form-label">上傳文件</label>
<div class="layui-input-inline">
<input type="text" name="attach" id="upload_message" lay-verify="required" autocomplete="off"
class="layui-input" readonly="readonly">
</div>
</div>
<div class="layui-inline">
<img id='img_delete' src="{{ url_for('static', filename='images/delete.png')}}" onclick="do_delete()"
style="display: none;">
<button type="button" class="layui-btn" id="upload"><i class="layui-icon"></i>上傳文件</button>
</div>
上傳按鈕初始化及回調(diào)
layui.use(['upload', 'layer'], function () {
var upload = layui.upload;
var layer = layui.layer;
upload.render({
elem: '#upload'
, url: '/upload'
, accept: 'file'
, exts: 'txt'
, size: 2048
, done: function (res) {
console.log(res);
if (res.code === 0) {
layer.msg(res.filename + '上傳成功');
$("#upload_message").val(res.filename);
$("#img_delete").show()
} else {
layer.alert('上傳失敗');
$("#upload_message").val('上傳失??!');
}
}
});
})
當(dāng)然允許上傳,同時(shí)也應(yīng)該允許對(duì)以刪除文件進(jìn)行刪除
@app.route('/delete', methods=['GET'])
def delete_file():
if request.method == 'GET':
filename = request.args.get('filename')
timestamp = request.args.get('timestamp')
logger.debug('delete file : %s, timestamp is %s' % (filename, timestamp))
try:
fullfile = os.path.join(UPLOAD_PATH, filename)
if os.path.exists(fullfile):
os.remove(fullfile)
logger.debug("%s removed successfully" % fullfile)
return jsonify({'code': 0, 'msg': ''})
else:
return jsonify({'code': -1, 'msg': 'File not exist'})
except Exception as e:
logger.debug("delete file error %s" % e)
return jsonify({'code': -1, 'msg': 'File deleted error'})
else:
return jsonify({'code': -1, 'msg': 'Method not allowed'})
刪除按鈕初始化及回調(diào)處理
function do_delete() {
var filename = $("#upload_message").val();
layui.use(['upload', 'layer'], function () {
var layer = layui.layer;
$.ajax({
url: '/delete?filename=' + filename + "×tamp=" + new Date().getTime()
, type: 'GET'
, success: function (response) {
console.log(response)
if (response.code == 0) {
layer.msg('"' + filename + '"刪除成功!');
$("#upload_message").val('')
$("img_delete").hide()
} else {
layer.msg('"' + filename + '"刪除失?。?);
}
}
})
})
}
實(shí)現(xiàn)效果

源碼參考:flask-sqlalchemy-web
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python Web框架Flask下網(wǎng)站開(kāi)發(fā)入門實(shí)例
- 一個(gè)基于flask的web應(yīng)用誕生 用戶注冊(cè)功能開(kāi)發(fā)(5)
- Flask web開(kāi)發(fā)處理POST請(qǐng)求實(shí)現(xiàn)(登錄案例)
- Flask框架web開(kāi)發(fā)之零基礎(chǔ)入門
- Python使用Web框架Flask開(kāi)發(fā)項(xiàng)目
- Python Flask框架開(kāi)發(fā)之運(yùn)用SocketIO實(shí)現(xiàn)WebSSH方法詳解
- 一步步講解利用Flask開(kāi)發(fā)一個(gè)Web程序
相關(guān)文章
手把手教你怎么用Python實(shí)現(xiàn)zip文件密碼的破解
之前在家里的老電腦中,發(fā)現(xiàn)一個(gè)加密zip壓縮包,由于時(shí)隔太久忘記密碼了,依稀記得密碼是6位字母加數(shù)字,網(wǎng)上下載了很多破解密碼的軟件都沒(méi)有效果,于是想到自己用Python寫一個(gè)暴力破解密碼的腳本,需要的朋友可以參考下2021-05-05
Python 列表推導(dǎo)式與字典推導(dǎo)式的實(shí)現(xiàn)
本文主要介紹了Python 列表推導(dǎo)式與字典推導(dǎo)式的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12
利用Python校準(zhǔn)本地時(shí)間的方法教程
這篇文章主要給大家介紹了關(guān)于如何利用Python校準(zhǔn)本地時(shí)間的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
Python threading.local代碼實(shí)例及原理解析
這篇文章主要介紹了Python threading.local代碼實(shí)例及原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
解決python讀取幾千萬(wàn)行的大表內(nèi)存問(wèn)題
今天小編就為大家分享一篇解決python讀取幾千萬(wàn)行的大表內(nèi)存問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06

