Search code examples
pythonangularjsflaskdownloadmongodump

Downloading an archive created with mongodump


I am trying to download remotely (i.e. through a browser) a Mongo dump from server using the mongodump command.

The backend is a Flask server and is like this:

@api.route('/export', methods=['GET'])
def exportDb():
    subprocess.check_output(['mongodump','--archive=db.gz', '--gzip', '--db', 'my_db'])
    response = make_response(open('db.gz', 'r').read())
    response.headers["Content-Disposition"] = "attachment; filename=db.gz"
    return response

The frontend uses AngularJs and looks like this:

    $http({
        method: 'GET',
        url: '/intro/export'
    }).then(function(response) {
        var blob = new Blob([response.data], {type: 'application/zip, application/octet-stream'});
        var objectUrl = URL.createObjectURL(blob);
        window.open(objectUrl);
    }

The archive is created correctly on the server side, but I can't manage to send it across to the client. When the request is sent, a new tab is opened for downloading a file named after a guid, so not "db.gz", and that file cannot be opened with any archive client, so I must have missed something either when sending it or saving it.

Any help would be very much appreciated.


Solution

  • So I've done it like this:

    @api.route('/exportDB', methods=['GET'])
    def exportDB():
        subprocess.check_output(['mongodump','--archive=db.gz', '--gzip', '--db', 'my_db'])
        response = send_from_directory("path/to/folder", 'db.gz', as_attachment=True)
        response.headers["Content-Type"] = "application/javascript"
        return response
    

    On client side I have:

    $http({
        method: 'GET',
        url: '/intro/exportDB',
        responseType: 'blob'
    }).then(function(response) {
        var data = new Blob([response.data]);
        saveAs(data, "db.gz");
     }
    

    Where saveAs is from Filesaver.js from here