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

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

风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com

稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!

昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。

这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。

而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?