[聚合文章] flask 项目中使用 bootstrapFileInput(基础篇)

CSS 2017-12-19 16 阅读

bootstrap 为 flask 使用人员提供了一个非常优美且有效的前端页面组件,但是完美之处还存在些许缺陷,比如文件的上传功能.而 bootstrap-fileinput 是基于 bootstrap 的控件,非常完美的填补了这个空缺.

注意: 本文是基于 bootstrap-fileinput v4.4.2. github 地址: https://github.com/kartik-v/bootstrap-fileinput

注意: 本文是主要是以 http://plugins.krajee.com/file-input/demo 示例为基础进行讲解.

创建蓝图 basic

创建方法请参照 flask 项目中使用 bootstrapFileInput(构建篇) 中 lib 蓝图的创建方法,此处不在赘述.

构建基础 html 模板

app/basic/templates/basic_common/base.html 内容如下:

<!DOCTYPE html><html lang="zh">    <head>        <meta charset="utf-8">        <meta http-equiv="X-UA-Compatible" content="IE=edge">        <meta name="viewport" content="width=device-width, initial-scale=1">        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->        <meta name="description" content="">        <meta name="author" content="">        <link rel="icon" href="{{ url_for('lib.static', filename='favicon.ico')}}">        <title>{% block title %}{% endblock %}</title>        {% block css %}            <!-- 新 Bootstrap 核心 CSS 文件 -->            <link rel="stylesheet" href="{{ url_for('lib.static', filename='css/bootstrap.min.css') }}">            <!-- 可选的Bootstrap主题文件(一般不用引入) -->            <link rel="stylesheet" href="{{ url_for('lib.static', filename='css/bootstrap-theme.min.css') }}">            <!-- 个性化主题文件 -->            <!-- font-awesome样式主题文体 -->            <link href="{{ url_for('lib.static',filename='css/font-awesome.css') }}" media="all" rel="stylesheet" type="text/css" />            <!-- fileinput样式主题文体 -->            <link href="{{ url_for('lib.static',filename='css/fileinput.min.css') }}" media="all" rel="stylesheet" type="text/css" />        {% endblock %}        {% block js %}            <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->            <script src="{{ url_for('lib.static', filename='js/jquery.min.js') }}"></script>            <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->            <script src="{{ url_for('lib.static', filename='js/bootstrap.min.js') }}"></script>            <!-- 个性化 js 文件 -->            <!-- piexif.min.js is only needed if you wish to resize images before upload to restore exif data.             This must be loaded before fileinput.min.js -->            <script src="{{ url_for('lib.static',filename='js/plugins/piexif.min.js') }}" type="text/javascript"></script>            <!-- sortable.min.js is only needed if you wish to sort / rearrange files in initial preview.                 This must be loaded before fileinput.min.js -->            <script src="{{ url_for('lib.static',filename='js/plugins/sortable.min.js') }}" type="text/javascript"></script>            <!-- purify.min.js is only needed if you wish to purify HTML content in your preview for HTML files.                 This must be loaded before fileinput.min.js -->            <script src="{{ url_for('lib.static',filename='js/plugins/purify.js') }}" type="text/javascript"></script>            <!-- the main fileinput plugin file -->            <script src="{{ url_for('lib.static',filename='js/fileinput.min.js') }}"></script>            <!-- optionally if you need a theme like font awesome theme you can include                it as mentioned below -->            <script src="{{ url_for('lib.static',filename='js/themes/fa/theme.min.js') }}"></script>            <!-- optionally if you need translation for your language then include                locale file as mentioned below -->            <script src="{{ url_for('lib.static',filename='js/locales/zh.js') }}"></script>        {% endblock %}    </head>    <body>        <div class="container">            <div class="row">                <div class="col-xs-12 col-sm-offset-2">                    <div class="col-xs-12 col-sm-8">                        {% block content %}                        {% endblock %}                    </div>                </div>            </div><!--/row-->        </div><!--/.container-->    </body></html>

base.html 模板引入 css 和 js 时的几个坑

注意 css 和 js 文件的导入顺序

  • 首先需要导入的 js 文件是 jquery.js.
  • 第二需要导入 bootstrap 相关的 css 和 js.
  • 第三需要导入 fileinput 相关的 css 和 js, 请注意项目中的注释, 相关的文件导入也需要有先后顺序的要求.

注意版本问题

  • 此项目所需的 jquery 是 jQuery v2.1.1.
  • 此项目所需的 bootstrap 是 v3.3.7 版本
  • 此项目所需的 fileinput 是 v4.4.2 的版本.

其它版本可能会有所不同.

注意 fileinput 使用模式

fileinput 有两种使用模式,一种是利用 form 提交,一种是 ajax 方式提交.其中 ajax 提交方式,需要从 js 中进行设置, 并将类样式 class 设置为 file-loading. 而非 ajax 提交方式需要引入 form 表单, 类样式 class 需设置为 file, 本基础示例都需要引入 form 表单.

基础示例 1

模板内容

app/basic/templates/example_1.html 内容如下:

{% extends 'basic_common/base.html' %}{% block content %}<h1>基本示例1 -- 自动展示缩略图</h1><label class="control-label">Select File</label><form method="post" role="form" enctype="multipart/form-data">    <input id="input-1" name="input-1" type="file" class="file"></form>{% endblock %}{% block title %}    基本示例1 -- 自动展示缩略图{% endblock %}

知识点:

  1. 需要引入 form 表单, 并支持文件上传, 需设置 enctype="multipart/form-data".
  2. 由于 flask 项目是以 html 标签的 name 属性进行选择元素, 该 input 标签中需要设置 name 属性.
  3. class 需要设置为 'file'.
  4. input 标签的 type 属性要设置为 file, 以便支持文件上传.
  5. input 标签由于没有引入 multiple 属性, 故不能实现选择多文件功能.

视图函数

app/basic/views.py 内容如下:

# -*- coding:utf-8 -*-__author__ = '东方鹗'from flask import render_template, request, current_app, redirect, url_forfrom . import basicfrom werkzeug.utils import secure_filenameimport osdef allowed_file(filename):    ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])    return '.' in filename and \           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS@basic.route('/example_1', methods=['GET', 'POST'])def example_1():    if request.method == 'POST':        file = request.files['input-1']        if file and allowed_file(file.filename):            filename = secure_filename(file.filename)            file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))    return render_template('example_1.html')

知识点:

  1. allowed_file 函数是为了检查所上传的文件的格式, 主要实现方法是通过文件后缀来判断文件的格式. 参考文档: http://docs.jinkan.org/docs/flask/patterns/fileuploads.html
  2. secure_filename 函数是为了让用户上传的文件的文件名更安全. 参考文档: http://werkzeug.pocoo.org/docs/0.12/utils/#werkzeug.utils.secure_filename
  3. request.files['input-1'] 是为了获得上传的文件的对象. 此处的 'input-1' 对应的是 html 模板中 input 标签的 name 属性. 获取多个上传的文件需要用到 request.files.getlist('name属性标签'), 可得到一个文件对象的列表.
  4. 上传的路径是在 config.py 文件中设置的 UPLOAD_FOLDER 变量.

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。