Python Flask 图片上传与下载

Python Flask 图片上传与下载

码农世界 2024-05-27 前端 75 次浏览 0个评论

Python代码

#encoding:utf-8
#!/usr/bin/env python
from werkzeug.utils import secure_filename
from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
basedir = os.path.abspath(os.path.dirname(__file__))
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF'])
 
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
 
 
@app.route('/')
def upload_test():
    ip = request.remote_addr
    print(ip)
    return render_template('up.html')
 
 
# 上传文件
@app.route('/up_photo', methods=['post'], strict_slashes=False)
def api_upload():
    ip = request.remote_addr
    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'],ip)
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    f = request.files['photo']
    if f and allowed_file(f.filename):
        fname = secure_filename(f.filename)
        print (fname,f.filename,file_dir)
        f.save(os.path.join(file_dir, f.filename))
        return render_template('up.html',name="已成功上传:"+f.filename)
    else:
        return jsonify({"error": 1001, "msg": "file type error"})
 
@app.route('/download/', methods=['GET'])
def download(filename):
    ip = request.remote_addr
    filename = ip + "/" + filename
    if request.method == "GET":
        if os.path.isfile(os.path.join('upload', filename)):
            return send_from_directory('upload', filename, as_attachment=True)
        else:
            return jsonify({"error": 1001, "msg": filename + " not exist!"})
# show photo
@app.route('/show/', methods=['GET'])
def show_photo(filename):
    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
    if request.method == 'GET':
        if filename is None:
            pass
        else:
            image_data = open(os.path.join(file_dir, '%s' % filename), "rb").read()
            response = make_response(image_data)
            response.headers['Content-Type'] = 'image/png'
            return response
    else:
        pass
 
 
if __name__ == '__main__':
    app.run(threaded=True)

网页代码

up.html 注意放到templates目录下,具体代码如下




    
    Title


    



转载请注明来自码农世界,本文标题:《Python Flask 图片上传与下载》

百度分享代码,如果开启HTTPS请参考李洋个人博客
每一天,每一秒,你所做的决定都会改变你的人生!

发表评论

快捷回复:

评论列表 (暂无评论,75人围观)参与讨论

还没有评论,来说两句吧...

Top