从蟒蛇下载文件到angularjs蟒蛇、文件、angularjs

2023-09-13 04:19:34 作者:初遇

我有这样的code,我想用户和客户端可以下载该文件。

I have this code which I want that user and client can download the file.

这是我的服务:

 DownLoad: function (data) {
        return $http({
          url: urlBase + 'export_file/',
          headers: {'Content-Type': undefined},
          data: data,
          method: 'POST'
        });
      }
    };

在code以上将作为我的连接​​器,Python和angularjs

the code above will serve as my connector for both python and angularjs

这是我的Python code这是我想要的结果传递给我的angularjs:

And this is my python code which I want the result to pass to my 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它作为数据的接收器:

And this is my angularjs which serve as the receiver of data:

$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中的数据始终保存到服务器用户的主目录。我也想在客户端用户下载,但可以保存到自己想要的下载文件夹中。有人能帮助我吗?我还在困惑如何传递数据。谢谢你。

Right now when I run this, the data inside my python always save into the home directory of the server user. I want also the user in the client to download it but can save into their desired download folder. Can someone help me? I'm still confused on how to pass the data. Thank you.

推荐答案

我不会在angularjs部分评论。你的问题在​​于瓶是如何处理您的请求。

I wont comment on the angularjs portion. Your problem lies with how flask is handling your request.

由于烧瓶结构类似下面。

Given a flask structure like the one below.

├── flasksandbox.py
├── static
│   └── downloadThis.txt
└── templates
    └── empty.html

和你想允许用户下载一个名为downloadThis.txt文件

And you want to allow user to download the file called 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()

如果你需要一个流文件,而不是(例如,如果你的文件是一个非常巨大的,或者你想生成它飞)检查出的 http://flask.pocoo.org/docs/0.10/patterns/streaming/ ,则可以执行以下操作:

If you need to stream a file instead (for instance if you file is a really huge or you want to generate it on the fly) check out http://flask.pocoo.org/docs/0.10/patterns/streaming/ , you can do the following :

@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"})

最后,标题 {内容处置:附件文件名=的text.txt} 将告诉浏览器处理的响应下载文件附件,而不是显示在浏览器和文件名=的text.txt将成为默认的文件名

At last, the headers { "Content-Disposition" :"attachment"filename=text.txt"} will tell the browser handling the response to download the file as an attachment instead of displaying on the browser and the filename=text.txt will be default filename

由send_file(),通过提供参数 as_attachment = TRUE ,这个头信息不能为自动添加到您的通过烧瓶响应

In send_file(), by providing the argument as_attachment=True, this header infomation is automatically added to your response by flask

 
精彩推荐
图片推荐