欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-05-30 19:50:17
本章我们介绍flask web开发中涉及的文件上传模块 定义后台接收处理逻辑 # http://flask.pocoo.org/docs/0.12/patter...

本章我们介绍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 + "&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开发入门之文件上传(八)

源码参考:   

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