The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Question about upload the photo to user table

JackieZhang
Tera Contributor

Hi all,

I want to write a scripted api to upload the photo to user table. Here is my code but failed. Please help to correct the code.

 

(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

    var requestBody = request.body.dataString;
    var parser = new global.JSON();
    var parsedData = parser.decode(requestBody);
    var correlation_id = parsedData.userID;
    //var fileName = 'photo';
    var fileContentType = parsedData.contentType;
    var fileData = parsedData.fileData;
    var rec = new GlideRecord('sys_user');
    rec.addQuery('u_correlation_id', correlation_id);
    rec.query();
    if (rec.next()) {
        var attachment_request = new sn_ws.RESTMessageV2();
        attachment_request.setEndpoint(endPoint);
        attachment_request.setHttpMethod('POST');
        var user = 'xxx';
        var password = 'xxxxx';
        attachment_request.setBasicAuth(user, password);
        attachment_request.setRequestHeader("Accept", "application/json");
        attachment_request.setRequestHeader("Content-Type", fileContentType);
        attachment_request.setRequestBody(fileData);
        var attachment_response = attachment_request.execute();
        response.setBody(attachment_response.responseBody);
        response.setStatus(attachment_response.getStatusCode());
    } else {
        var error = "The User ID " + correlation_id + " not found in ServiceNow";
        var responseBodyFailure = {
            "error": error
        };
        responseBodyFailure.status = "Failure";
        response.setStatus(404);
        response.setBody(responseBodyFailure);
    }

})(request, response);
10 REPLIES 10

Rafael Batistot
Kilo Patron

Ankur Bawiskar
Tera Patron
Tera Patron

@JackieZhang 

what error it gave?

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Here is my lastest code.  the attahment has been added but the photo was broken and can't be opened

(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {


    var requestBody = request.body.dataString;
    var parser = new global.JSON();
    var parsedData = parser.decode(requestBody);
    var contentType = parsedData.contentType;
    var image = parsedData.data;
    var userID = parsedData.userID;

    if (!image || image == null || image == undefined) {
        response.setStatus(400);
        return response.setBody({
            message: "There was no image in the body of the request",
        });
    }

    var user_GR = getTheUser(userID);

    if (!user_GR) {
        gs.error("ScriptedWebService [Photos] User not found: " + userID);
        response.setStatus(404);
        return response.setBody({
            message: "That user does not exist in the system",
        });

    }

    var message = '';

    // clearPhotos(user_GR, messages);

    message = attachPhotoBinary(user_GR, image, contentType);

    response.setStatus(200);
    return response.setBody({
        "status": "success",
        "message": message
    });

})(request, response);

function getTheUser(userId) {
    var user_GR = new GlideRecord('sys_user');
    user_GR.addQuery('u_correlation_id', userId);
    user_GR.query();
    if (user_GR.next()) {
        return user_GR;
    }
    return false;
}

/**
 *
 * Delete the previous photo's stored on the user profile
 *
 */

function clearPhotos(userGR, messages) {
    var attachments_GR = new GlideRecord('sys_attachment');
    attachments_GR.addQuery('table_name', 'ZZ_YYsys_user');
    attachments_GR.addQuery('table_sys_id', userGR.sys_id);
    attachments_GR.addQuery('file_name', 'photo');
    attachments_GR.query();

    while (attachments_GR.next()) {
        attachments_GR.deleteRecord();
        messages.push("Deleted photo: " + attachments_GR.sys_id);
    }
    return messages;
}

/**
 *
 * Attach the photo.
 * The fields within the sys_attachment record
 * should exactly match what's sent. The KB article in the code doc
 * at the top explains why
 *
 */

function attachPhotoBinary(user_GR, imageBinary, contentType) {
    var photo_GR = new GlideSysAttachment();
    var photo_sys_id = photo_GR.write(user_GR, 'photo', contentType, imageBinary);
    gs.info("photo_sys_id:" + photo_sys_id);

    var attachment_GR = new GlideRecord('sys_attachment');
    attachment_GR.addQuery('sys_id', photo_sys_id);
    attachment_GR.query();

    if (attachment_GR.next()) {
        attachment_GR.table_name = "ZZ_YYsys_user";
        attachment_GR.table_sys_id = user_GR.sys_id;
        attachment_GR.content_type = 'image/jpeg';
        attachment_GR.update();
        var message = "Attached photo: " + photo_sys_id;
    } else {
        var message = "Failed to attach photo: " + photo_sys_id;
    }
    return message;
}
JackieZhang_0-1758546033568.png

By the way,I used this online tools to transform the image to base64 string.  https://www.jyshare.com/front-end/59/

@JackieZhang 

does the request body contain base64encoded data?

if yes then you are in global scope or scoped app? where did you write the code?

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader