美文网首页Flask
如何用Flask写一个文件(图片)上传下载的API?

如何用Flask写一个文件(图片)上传下载的API?

作者: 宁静世界 | 来源:发表于2018-06-26 21:29 被阅读0次

    文件上传完整代码

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    from flask import request, jsonify, send_from_directory, abort
    from werkzeug.utils import secure_filename
    from flask import Flask, render_template, jsonify, request
    import time
    import os
    import base64
    
    app = Flask(__name__)
    UPLOAD_FOLDER = 'upload'
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    basedir = os.path.abspath(os.path.dirname(__file__))
    ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'xls', 'JPG', 'PNG', 'xlsx', 'gif', 'GIF'])
    
    
    # 用于判断文件后缀
    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
    
    
    # # 用于测试上传,稍后用到
    # @app.route('/test/upload')
    # def upload_test():
    #     return render_template('upload.html')
    
    
    @app.route("/api/download/<filename>", methods=['GET'])
    def download(filename):
        if request.method == "GET":
            if os.path.isfile(os.path.join('upload', filename)):
                return send_from_directory('upload', filename, as_attachment=True)
            abort(404)
    
    
    # 上传文件
    @app.route('/api/upload', methods=['POST'], strict_slashes=False)
    def api_upload():
        file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)
        f = request.files['myfile']  # 从表单的file字段获取文件,myfile为该表单的name值
        if f and allowed_file(f.filename):  # 判断是否是允许上传的文件类型
            fname = secure_filename(f.filename)
            print fname
            ext = fname.rsplit('.', 1)[1]  # 获取文件后缀
            unix_time = int(time.time())
            new_filename = str(unix_time) + '.' + ext  # 修改了上传的文件名
            f.save(os.path.join(file_dir, new_filename))  # 保存文件到upload目录
            token = base64.b64encode(new_filename)
            print token
            return jsonify({"code": 0, "errmsg": "上传成功", "token": token, "fileName": "/api/download/" + new_filename})
        else:
            return jsonify({"code": 1001, "errmsg": "上传失败"})
    
    
    if __name__ == '__main__':
        app.run(debug=True)
    
    
    

    新建一个upload.html测试

    <form id="form1" method="post" action="http://127.0.0.1:5000/api/upload" enctype="multipart/form-data">
        <div>
            <input id="File1" type="file" name="myfile"/>
            <input type="submit">提交</input>
        </div>
    </form>
    

    如何下载?

    上传完成后会返回fileName字段,用域名加fileName即可访问图片

    http://127.0.0.1:5000/api/download/xxx.png

    有一个坑值得注意,如果你的文件名是全中文,Flask是无法识别的(Flask底层源码设计的问题),处理方式也很简单,自己最好做好容错处理,重新定义一个名字

    相关文章

      网友评论

        本文标题:如何用Flask写一个文件(图片)上传下载的API?

        本文链接:https://www.haomeiwen.com/subject/wlfvyftx.html