flask实现文件的上传和下载

  • 文件上传和下载前端的实现
    点击下载模板

     

  • 文件上传和下载的后端实现
    # 以安全的方式来获取用户的文件名
    # @app.route('/upload', methods=['get', 'post'])
    # def upload():
    #     servers = request.files.get('servers')
    #     filename = secure_filename(servers.filename)  # servers.filename获取上传的文件名
    #     servers.save('/tmp/{0}'.format(filename))  # 保存路径/tmp/文件名
    #     return "Upload Success!"
    
    
    # 使用随机数(时间戳)来保存文件
    @app.route('/upload', methods=['get', 'post'])
    def upload():
        servers = request.files.get('servers')
        ramname = int(time.time() * 1000)
        servers.save('/tmp/{0}'.format(ramname))
        return "Upload Success!"
    
    
    @app.route('/download')
    def download():
        # os.path.realpath(__file__)打印出来的是当前路径/soft/flask/day1/wenwen.py
        # os.path.dirname(os.path.realpath(__file__))打印出来的是/soft/flask/day1/
        current_dir = os.path.dirname(os.path.realpath(__file__))
        return send_from_directory(current_dir+"/static", "flask_download_test.docx", as_attachment=True)

     

你可能感兴趣的:(flask)