将文件从python下载到angularjs

将文件从python下载到angularjs,python,angularjs,web-services,flask,Python,Angularjs,Web Services,Flask,我有这个代码,我希望用户和客户端可以下载该文件 这是我的服务: DownLoad: function (data) { return $http({ url: urlBase + 'export_file/', headers: {'Content-Type': undefined}, data: data, method: 'POST' }); } }; 上面

我有这个代码,我希望用户和客户端可以下载该文件

这是我的服务:

 DownLoad: function (data) {
        return $http({
          url: urlBase + 'export_file/',
          headers: {'Content-Type': undefined},
          data: data,
          method: 'POST'
        });
      }
    };
上面的代码将作为python和angularjs的连接器

这是我的python代码,我想把结果传递给我的angularjs:

@api.route("/export_file/", methods=["POST"])
 def export_file():
  if request.method == 'POST':

    home = expanduser("~")
    home2 = os.path.join(home,"try.txt")
    ap = csv.writer(file(home2,'wb'))
    ap.writerows(["HELLOW WORLD"])
    db.session.commit()

    return jsonify({'success': True})
这是我的angularjs,作为数据的接收器:

$scope.DLFILE = function() {
                        downloading.DownLoad()
                        .success(function(data, status, headers, config) {console.log(data);
                        if (data.success) {
                            $scope.ExportDate={}
                            var blob = new Blob([data], {type: "text/plain;charset=utf-8"}); #I add this one which came from other source, and I hope this may help to save my data.
                            saveAs(blob, "hello world.txt");
                            console.log('success!');

                        }
                        })
                        .error(function(data, status, headers, config) {

                            console.log('error in downloading!');

                        });

                // }
            };

现在,当我运行它时,python中的数据总是保存到服务器用户的主目录中。我也希望客户端的用户下载它,但可以保存到他们想要的下载文件夹。有人能帮我吗?我仍然对如何传递数据感到困惑。谢谢。

我不会对angularjs部分发表评论。您的问题在于flask如何处理您的请求

给定一个烧瓶结构,如下所示

├── flasksandbox.py
├── static
│   └── downloadThis.txt
└── templates
    └── empty.html
您希望允许用户下载名为downloadThis.txt的文件

您的路线将是:

from flask import Flask, render_template, send_file

app = Flask(__name__)


@app.route('/')
def get_file():
    return send_file('static/downloadThis.txt',as_attachment=True)

if __name__ == '__main__':
    app.run()
如果您需要流式传输文件(例如,如果您的文件非常大,或者您希望动态生成文件),请签出,您可以执行以下操作:

@app.route('/stream')
def get_file_stream():
    def generate():
        for letters in "this is suppose to be a big csv file iterator or something":
            yield letters + '\n'


    return Response(generate(),
                    mimetype="text/plain",
                    headers={"Content-Disposition":
                               "attachment;filename=test.txt"})
最后,标题
{“Content Disposition”:“attachment”filename=text.txt“}
将告诉处理响应的浏览器将文件作为附件下载,而不是显示在浏览器上,并且filename=text.txt将是默认文件名

send_file()
中,通过提供参数
作为_attachment=True
,此标题信息将自动添加到您的响应中