AngularJS和Python Flask中的下载文件问题

时间:2018-09-07 11:28:31

标签: angularjs flask cors

我需要从服务器下载一个zip文件。下面是相同的代码。当我对WS URL进行卷曲时,将下载zip文件。但是,当我用角度代码在浏览器中执行相同的操作时,却没有发生。

也无法找出任何错误。

  $scope.downloadData = function () {
        console.log ('Entering in to Download Method')
        var req = {
        method: 'GET',
        url: 'http://localhost:5000/download/',
        headers: {
        'Content-Type': 'application/zip',
         'Access-Control-Allow-Origin': '*',
         'Access-Control-Allow-Credentials': 'true',
         'Access-Control-Allow-Methods': 'POST,GET,OPTIONS',
         'Access-Control-Allow-Headers': 'Content-Type'
        }
        }
        return $http(req).then(function (resp) {
        console.log(resp);
        headers = headers();
        var filename = headers['x-filename'];
        var contentType = headers['content-type'];
        var linkElement = document.createElement('a');
        try {
            var blob = new Blob([resp], { type: contentType });
            var url = window.URL.createObjectURL(blob);

            linkElement.setAttribute('href', url);
            linkElement.setAttribute("download", filename);

            var clickEvent = new MouseEvent("click", {
                "view": window,
                "bubbles": true,
                "cancelable": false
            });
            linkElement.dispatchEvent(clickEvent);
        } catch (ex) {
            console.log(ex);
        }
    });
        };

从浏览器控制台中,我收到以下错误。

OPTIONS http://localhost:5000/download/logs.zip 0 ()


Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:5000/download/logs.zip","headers":{"Accept":"application/json, text/plain, */*","kbn-version":"6.2.4"}},"statusText":""}

按如下所示安装服务器端

@app.route('/download', methods=['POST','GET','OPTIONS'])
def index():
    log_folder = '/home/ubuntu/kibana_lt/src/'
    files = os.listdir(log_folder)
    files_log = []
    for f in files:
        if f.endswith('.log'):
            filename = os.path.join(log_folder, f)
            print (filename);
            files_log.append(filename)
    memory_file = BytesIO()
    ZipFile = zipfile.ZipFile("logs.zip", "w" )
    for individualFile in files_log:
        ZipFile.write(os.path.basename(individualFile), compress_type=zipfile.ZIP_DEFLATED)
    response = make_response(send_file(memory_file, mimetype='application/octet-stream',attachment_filename='logs.zip', as_attachment=True))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    return  response
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000,debug = True)

0 个答案:

没有答案