金狮镖局 Design By www.egabc.com
本章我们介绍Flask Web开发中涉及的文件上传模块
定义后台接收处理逻辑
# 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
前台页面代码
<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="/UploadFiles/2021-04-08/delete.png')}}">上传按钮初始化及回调
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('上传失败!'); } } }); })当然允许上传,同时也应该允许对以删除文件进行删除
@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'})删除按钮初始化及回调处理
function do_delete() { var filename = $("#upload_message").val(); layui.use(['upload', 'layer'], function () { var layer = layui.layer; $.ajax({ url: '/delete"×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 + '"删除失败!'); } } }) }) }实现效果
源码参考:flask-sqlalchemy-web
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
标签:
Flask,Web,文件上传
金狮镖局 Design By www.egabc.com
金狮镖局
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
金狮镖局 Design By www.egabc.com
暂无Flask Web开发入门之文件上传(八)的评论...
更新日志
2024年11月20日
2024年11月20日
- 群星《一人一首成名曲》1998 台湾金碟珍藏版[WAV+CUE][1.1G]
- 陈百强2024-《凝望》头版限量编号MQA-UHQCD[WAV+CUE]
- 测试示范《监听天碟3》头版限量编号LECD[WAV+CUE]
- 陈瑞《爱你到天荒地老HQ》头版限量[低速原抓WAV+CUE]
- 徐小凤 《徐小凤殿堂18首》24K金碟[WAV+CUE]
- 保时捷原厂车载爆棚动态试音碟《Panamera_Soundtrack》DTS[WAV分轨][1G]
- 容祖儿《小小》香港首版 [WAV+CUE][1.1G]
- 莫文蔚《拉活…》SONY [WAV+CUE][1G]
- Beyond《极品天碟》LPCD45II首批限量版[WAV+CUE][1.7G]
- HIFI示范巅峰之作《情解药·Hi-Fi心魂》2CD[WAV+CUE]
- 房东的猫2021-关于彻夜不眠的事情(EP)[青柴文化][WAV+CUE]
- 群星.1993-一曲成名·青春无悔【飞碟】【WAV+CUE】
- 张芸京.2016-失败的高歌【泡耳音乐】【WAV+CUE】
- 天籁女声《2024第31届上海国际高端音影展纪念CD》[WAV+CUE][1.1G]
- 姚斯婷 《敢爱敢做》头版限量编号24K金碟[低速原抓WAV+CUE][1.2G]