Flask Web开发入门之文件上传(八)


Posted in Python onAugust 17, 2018

本章我们介绍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="{{ 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>

上传按钮初始化及回调

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?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 + '"删除失败!');
          }
        }
      })
    })
  }

实现效果

Flask Web开发入门之文件上传(八)

源码参考:flask-sqlalchemy-web   

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中请使用isinstance()判断变量类型
Aug 25 Python
python实现连接mongodb的方法
May 08 Python
利用Python+Java调用Shell脚本时的死锁陷阱详解
Jan 24 Python
解决csv.writer写入文件有多余的空行问题
Jul 06 Python
PyCharm设置每行最大长度限制的方法
Jan 16 Python
python解析命令行参数的三种方法详解
Nov 29 Python
Windows下实现将Pascal VOC转化为TFRecords
Feb 17 Python
使用pyecharts1.7进行简单的可视化大全
May 17 Python
Python爬虫之爬取淘女郎照片示例详解
Jul 28 Python
浅析python函数式编程
Sep 26 Python
Python基于execjs运行js过程解析
Nov 27 Python
python利用opencv实现颜色检测
Feb 23 Python
python操作excel的方法
Aug 16 #Python
python3调用百度翻译API实现实时翻译
Aug 16 #Python
Python用于学习重要算法的模块pygorithm实例浅析
Aug 16 #Python
Python pygorithm模块用法示例【常见算法测试】
Aug 16 #Python
Python使用pickle模块报错EOFError Ran out of input的解决方法
Aug 16 #Python
Python使用pickle模块储存对象操作示例
Aug 15 #Python
Linux下多个Python版本安装教程
Aug 15 #Python
You might like
单一index.php实现PHP任意层级文件夹遍历(Zjmainstay原创)
2012/07/31 PHP
php实现excel中rank函数功能的方法
2015/01/20 PHP
php判断邮箱地址是否存在的方法
2016/02/13 PHP
PHP给前端返回一个JSON对象的实例讲解
2018/05/31 PHP
ThinkPHP like模糊查询,like多匹配查询,between查询,in查询,一般查询书写方法
2018/09/26 PHP
PHP explode()函数用法讲解
2019/02/15 PHP
javascript[js]获取url参数的代码
2007/10/17 Javascript
基于jquery+thickbox仿校内登录注册框
2010/06/07 Javascript
jquery实现类似EasyUI的页面布局可改变左右的宽度
2020/09/12 Javascript
jQuery实现的经典滑动门效果
2015/09/22 Javascript
javascript中new关键字详解
2015/12/14 Javascript
微信小程序  网络请求API详解
2016/10/25 Javascript
js以分隔符分隔数组中的元素并转换为字符串的方法
2016/11/16 Javascript
jQuery使用EasyUi实现三级联动下拉框效果
2017/03/08 Javascript
在 webpack 中使用 ECharts的实例详解
2018/02/05 Javascript
JS 自执行函数原理及用法
2019/08/05 Javascript
微信小程序仿今日头条导航栏滚动解析
2019/08/20 Javascript
layer 关闭指定弹出层的例子
2019/09/25 Javascript
vue.js+ElementUI实现进度条提示密码强度效果
2020/01/18 Javascript
vue实现图片懒加载的方法分析
2020/02/05 Javascript
Vue实现简单计算器
2021/01/20 Vue.js
Python version 2.7 required, which was not found in the registry
2014/08/26 Python
利用Python将时间或时间间隔转为ISO 8601格式方法示例
2017/09/05 Python
python GUI图形化编程wxpython的使用
2019/07/19 Python
python 字典套字典或列表的示例
2019/12/16 Python
python中uuid模块实例浅析
2020/12/29 Python
英国高端食品和葡萄酒超市:Waitrose
2016/08/23 全球购物
如何清空Session
2015/02/23 面试题
酒店销售主管岗位职责
2014/01/04 职场文书
结婚典礼证婚词
2014/01/08 职场文书
科技活动周标语
2014/10/08 职场文书
公司感恩节活动策划书
2014/10/11 职场文书
公司股份合作协议书
2014/12/07 职场文书
工作简报格式范文
2015/07/21 职场文书
vue-cli4.5.x快速搭建项目
2021/05/30 Vue.js
nginx搭建NFS网络文件系统
2022/04/14 Servers