Search code examples
javascriptgoogle-drive-apixmlhttprequest

How can I store part of an XMLHttpRequest response as a variable?


I'm using a modified version of this tutorial to upload files to Google Drive using a form.

Here's the relevant code:

$("#fUpload").on("change", function () {
        var uploadObj = $("[id$=fUpload]");
        var file = uploadObj.prop("files")[0];
        var metadata = {
            'title': file.name,
            'description': " ",
            'mimeType': file.type || 'application/octet-stream',
            "parents": [{
                "kind": "drive#file",
                "id": "0B5zM5ktmwJ2fN0c3RWYxWC1rUzQ"
            }]
        };
        var arrayBufferView = new Uint8Array(file);
        var uploadData = new Blob(arrayBufferView, {type: file.type || 'application/octet-stream'});
        try{
            var uploader =new MediaUploader({
                file: file,
                token: gapi.auth.getToken().access_token,
                metadata: metadata,
                params: {
                    convert:false,
                    ocr: false
                }
            });
            uploader.upload();
        }catch(exc){
            showErrorMessage("Error: " + exc);
            $("#fUpload").val(" ");
        }
    });

var MediaUploader = function (options) {
    var noop = function () { };
    this.file = options.file;
    this.contentType = options.contentType || this.file.type || 'application/octet-stream';
    this.metadata = options.metadata || {
        'title': this.file.name,
        'mimeType': this.contentType
    };
    this.token = options.token;
    this.onComplete = options.onComplete || noop;
    this.onProgress = options.onProgress || noop;
    this.onError = options.onError || noop;
    this.offset = options.offset || 0;
    this.chunkSize = options.chunkSize || 0;
    this.retryHandler = new RetryHandler();

    this.url = options.url;
    if (!this.url) {
        var params = options.params || {};
        params.uploadType = 'resumable';
        this.url = this.buildUrl_(options.fileId, params, options.baseUrl);
    }
    this.httpMethod = options.fileId ? 'PUT' : 'POST';
};

/**
* Initiate the upload.
*/
MediaUploader.prototype.upload = function () {
    var self = this;
    var xhr = new XMLHttpRequest();

    xhr.open(this.httpMethod, this.url, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + this.token);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('X-Upload-Content-Length', this.file.size);
    xhr.setRequestHeader('X-Upload-Content-Type', this.contentType);

    xhr.onload = function (e) {
        if (e.target.status < 400) {
            var location = e.target.getResponseHeader('Location');
            this.url = location;
            this.sendFile_();
        } else {
            this.onUploadError_(e);
        }
    } .bind(this);
    xhr.onerror = this.onUploadError_.bind(this);
    xhr.send(JSON.stringify(this.metadata));
};

/**
* Send the actual file content.
*
* @private
*/
MediaUploader.prototype.sendFile_ = function () {
    var content = this.file;
    var end = this.file.size;

    if (this.offset || this.chunkSize) {
        // Only bother to slice the file if we're either resuming or uploading in chunks
        if (this.chunkSize) {
            end = Math.min(this.offset + this.chunkSize, this.file.size);
        }
        content = content.slice(this.offset, end);
    }

    var xhr = new XMLHttpRequest();
    xhr.open('PUT', this.url, true);
    xhr.setRequestHeader('Content-Type', this.contentType);
    xhr.setRequestHeader('Content-Range', "bytes " + this.offset + "-" + (end - 1) + "/" + this.file.size);
    xhr.setRequestHeader('X-Upload-Content-Type', this.file.type);
    if (xhr.upload) {
        xhr.upload.addEventListener('progress', this.onProgress);
    }
    xhr.onload = function(event){
    var xhr = event.target;

    if (xhr.readyState === 4 && xhr.status === 200) {
        document.getElementById("target").innerHTML = xhr.responseText
    }


    xhr.onerror = this.onContentUploadError_.bind(this);
    xhr.send(content);
};

I need to store the ID specified in the response as a variable. The response body looks like this. The problem is I can't figure out how to get to it. I think the success handler should be taking care of this, but it's not:

/**
* Handle successful responses for uploads. Depending on the context,
* may continue with uploading the next chunk of the file or, if complete,
* invokes the caller's callback.
*
* @private
* @param {object} e XHR event
*/
MediaUploader.prototype.onContentUploadSuccess_ = function (e) {
    if (e.target.status == 200 || e.target.status == 201) {
        this.onComplete(e.target.response);

    } else if (e.target.status == 308) {
        this.extractRange_(e.target);
        this.retryHandler.reset();
        this.sendFile_();
    }
};

I've tried console.log(e.target.response), console.log(e.target.responseText), and

var response = e.target.response;
console.log(response);

Nothing seems to be working. I can't even get the console to output a string.

Sorry if it's something stupid, I'm still pretty noobish.


Solution

  • From your question's comments, looks like you have the response that you want. Simply declare a variable outside of the scope and assign the ID property of the response to it.

    var myId;
    MediaUploader.prototype.onContentUploadSuccess_ = function (e) {
        if (e.target.status == 200 || e.target.status == 201) {
            console.log(e.target.response); // assuming this is the result of "http://imgur.com/a/KgDQO"
            myId = e.target.response.id; // bam
            this.onComplete(e.target.response);
    
        } else if (e.target.status == 308) {
            this.extractRange_(e.target);
            this.retryHandler.reset();
            this.sendFile_();
        }
    };
    console.log(myId);