Welcome to Community Week 2025! Join us to learn, connect, and be recognized as we celebrate the spirit of Community and the power of AI. Get the details  

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);
1 ACCEPTED SOLUTION

@JackieZhang 

try this link where I shared solution to attach file via scripted rest api then enhance it based on your requirement. once the image is copied to record, simply query sys_attachment with this user sysId and update the table name as 'ZZ_YYsys_user'

Scripted Rest API to update incident with attachment 

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

View solution in original post

10 REPLIES 10

Rafael Batistot
Kilo Patron

Hi @JackieZhang 

 

this post might help you 

 

https://medium.com/@AServiceNowDev/updating-user-photos-via-rest-in-servicenow-f5da50c00627

If you found this response helpful, please mark it as Helpful. If it fully answered your question, consider marking it as Correct. Doing so helps other users find accurate and useful information more easily.

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