Python flask web基础(二)做一个上传图片文件的实例

12 篇文章 0 订阅

先看效果:

项目目录结构如下:

实现代码捡重要的贴给大家:

1)前端页面_base.html

{% from "common/_macro.html" import static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Ewangda</title>
    {% include "test/_head.html" %}
    {% block head %}{% endblock %}
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
                {% block page_title %}{% endblock %}

            <div class="main_content">
                {% block content %}{% endblock %}
            </div>
        </div>
    </div>
</div>
    <footer id="footer_group">
            © 2015-2035 上海集迪信息科技有限公司, 版权所有
            备案号:<a>沪ICP备xxxxxx号</a><br>
            管理员邮箱:<a>17280671@qq.com</a><br>
            地址:上海市杨浦区国定路323号
    </footer>
</body>
</html>

_head.html

{% from "common/_macro.html" import static %}

<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<link href="http://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="http://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">

<link rel="stylesheet" href="{{ static("test/css/_base.css") }}">
<script src="{{ static("test/js/_base.js") }}"></script>
{#layui#}
<script src="{{ url_for("static",filename="common/layui/layui.js") }}"></script>

<link rel="stylesheet" href="{{ url_for("static",filename="common/layui/css/layui.css") }}">

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

{#主页#}
<link rel="stylesheet" href="{{ static("common/css/index.css") }}">


{##提示框#}
<link rel="stylesheet" href="{{ static("common/sweetalert/sweetalert.css") }}">
<script src="{{ static("common/sweetalert/sweetalert.min.js") }}"></script>
<script src="{{ static("common/sweetalert/zlalert.js") }}"></script>

<script src="{{ static("common/js/zlajax.js") }}"></script>

upload.html

{% extends "test/_base.html" %}
{% from "common/_macro.html" import static %}
{% block head %}
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="{{ static("test/js/upload.js") }}"></script>

<style>
    .item img{
        width: 100%;
    }
			.file-box{
				display: inline-block;
				position: relative;
				height: 30px;
                line-height: 30px;
                border-radius: 5%;
				overflow: hidden;
				color:#fff;
				background-color: #5dc2f1;
			}
            .file-btn:hover{cursor: pointer;}
			.file-btn{
                border-radius: 5%;
				position: absolute;
				width: 100%;
				height: 100%;
				top: 0;
    			left: 0;
    			outline: none;
    			background-color: transparent;
    			filter:alpha(opacity=0);
				-moz-opacity:0;
				opacity: 0;
			}
    .cms-banner{
        border-radius: 10px;
        overflow: hidden;
        height: 250px;
        width: 100%
    }
    </style>

{%endblock%}

{% block content %}
    <div class="form-group">
                  <label class="col-sm-2 control-label">图片:</label>
                  <div class="col-sm-7">
                      <input type="text" class="form-control" name="image_url" placeholder="轮播图图片">
                  </div>
                    <div  class="col-sm-2 file-box" id="add-bbb">
                      <input type="file" class="col-sm-2 file-btn" id="file">添加图片
                  </div>

        <button class="ui primary loading button" id="loder" style="display: none">上传中</button>
    </div>
 <hr data-am-widget="divider" style="" class="am-divider am-divider-dashed am-no-layout">

                        <div>
                            <img src="" id="img_show" style="max-height: 150px;margin-bottom: 10px;">
                        </div>
{%endblock%}

2)js文件内容与后端进行数据交互

upload.js

$(function () {
    var file = $('#file');
    var imgage_url = $("input[name='image_url']");
    file.on('change', function (e) {
        $("#add-bbb").css('display','none');
        $("#loder").css('display','block');
        var img_url = e.currentTarget.files[0].name;
        var file = document.getElementById("file").files[0];
        var fm = new FormData();
        fm.append('file', file);
        zlajax.post({
            'url': '/test/upload/',
            processData: false,
            contentType: false,
            'data': fm,
            'success': function (data) {
                if (data['code'] == 200) {
                    swal('上传成功!');
                    imgage_url.val(data['data']);
                        $("#add-bbb").css('display','block');
                        $("#loder").css('display','none');
                    $("#img_show").attr("src", data['data']);
                }
            }
        })
    });
})

3)后端views.py实现文件保存及信息反馈

from flask import Blueprint,request, jsonify, render_template, json,session, redirect, flash,url_for,views,g
from app.utils import restful
from app.utils.upload import change_filename
from werkzeug.utils import secure_filename

import os

bp = Blueprint('test',__name__)

@bp.route('/test/upload/',methods=['POST','GET'])
# @login_required
def upload():
    if request.method == 'POST':
        # 定义上传目录,如果目录不存在,则自动创建
        UPLOAD_FOLDER = os.getcwd() + '/app/static/upload/'    # 上传后保存的本地路径
        file_dir = os.path.join(os.getcwd(), UPLOAD_FOLDER)#constants.
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)

        image = request.files['file']  # 获取前端提交过来的图片
        filename = secure_filename(change_filename(image.filename))  # 修改图片上传的图片名称
        file_path = os.path.join(UPLOAD_FOLDER, filename)  # 获取上传后的绝对路径
        image.save(file_path)  # 保存到本地
        return restful.success(data=os.path.join('/static/upload', filename))
    return render_template('test/upload.html')

最后两个工具文件的内容:

1)restful.py

#encoding:utf-8
from flask import jsonify


class HttpCode(object):
    Ok = 200
    ParamerError = 400
    Unauth = 401
    ServerError = 500

def RestfulResult(code,message,data):
    return jsonify({'code':code,'message':message,'data':data})



def success(message="",data=None):
    return RestfulResult(HttpCode.Ok,message=message,data=data)


def params_error(message="",data=None):
    return RestfulResult(HttpCode.ParamerError,message=message,data=data)

def unauth_error(message="",data=None):
    return RestfulResult(HttpCode.Unauth,message=message,data=None)

def server_error(message=""):
    return RestfulResult(HttpCode.ServerError,message=message,data=None)




2)upload.py

#encoding:utf-8
import os, sys
from datetime import datetime

#----gtj 用于上传文件的文件名修改
def change_filename(filename):
    dt = datetime.now()
    time = dt.strftime('%Y%m%d%H%M%S')
    filename = time+filename
    return filename


def percentage(consumed_bytes, total_bytes):
    if total_bytes:
        rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
        print('\r{0}% '.format(rate), end='')
        sys.stdout.flush()






总结:通过以上代码最终实现上传图片成功并显示图片及提示

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿桂天山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值