Send binary file with additional parameter using RESTMessageV2

Euro Fuenmayor
Tera Contributor

I am trying to send an MP4 file using RESTMessageV2, which, in addition to the binary file in the "content" field, must include a "docPath" field with the path where it will be deposited at the destination, with a content-type of multipart/form-data. For this, I am manually constructing the request body; the reason I am doing it this way is that using methods like setRequestBodyFromAttachment sets the file binary without the possibility of adding an additional part with the docPath data. The problem is that the file binary is not being handled correctly when adding it to the request body, as the file is uploaded but does not have the correct size and cannot be played.

 

Code executed on background script

 

 

 

Run the following code in a background script in the dev instance:

try {
     var attachmentSysId = 'd6de5fb5833496502f4fcddfeeaad3ed'; // video  Pieza MP4-20-1.mp4
 //var attachmentSysId = '809d465e83899210e34b9330feaad301'; // response.txt

    var attachment = new GlideSysAttachment();
    var attachmentRecord = new GlideRecord('sys_attachment');

    // Asegurarse de que se encuentra el registro del archivo
    if (attachmentRecord.get(attachmentSysId)) {
        var restMessage = new sn_ws.RESTMessageV2('OpenKM', 'createDocument');

        // Generar un boundary único
        var boundary = 'Boundary_' + gs.generateGUID();
        
        // Obtener el nombre del archivo
        var fileName = attachmentRecord.file_name;

        // Crear el cuerpo de la solicitud multipart
        var requestBody = "";

        // Parte para docPath
        requestBody += "--" + boundary + "\r\n";
        requestBody += "Content-Disposition: form-data; name=\"docPath\"\r\n\r\n";
        requestBody += "/okm:root/0710-10x-" + fileName + "\r\n";

        // Parte para el contenido del archivo
        requestBody += "--" + boundary + "\r\n";
        requestBody += "Content-Disposition: form-data; name=\"content\"; filename=\"" + fileName + "\"\r\n";
        requestBody += "Content-Type: " + attachmentRecord.content_type + "\r\n\r\n";

  gs.info('contentType: ' + attachmentRecord.content_type);
  gs.info('filename: ' + fileName);

        // Obtener el contenido del archivo como un array de bytes usando getBytes()
        var fileBytes = attachment.getBytes(attachmentRecord);
  gs.info('fileBytes: '+fileBytes);

  // Agregar el archivo binario al cuerpo multipart
  requestBody += fileBytes;

        // Conversion base64 -forma para conseguir que envio un documento con texto plano o compatible
        //var fileBytes64 = GlideStringUtil.base64Encode(fileBytes); 
  //var fileContent = GlideStringUtil.base64Decode(fileBytes64); 
        //requestBody += fileContent;

        // Cerrar el cuerpo multipart
        requestBody += "\r\n--" + boundary + "--\r\n";
      
        gs.info(requestBody);

        // Establecer el cuerpo de la solicitud completo
        restMessage.setRequestBody(requestBody);

  // Establecer el encabezado Content-Type con el boundary correcto
        restMessage.setRequestHeader("Content-Type", "multipart/form-data" );

        // Enviar la solicitud
        var response = restMessage.execute();
        var httpStatus = response.getStatusCode();
        var responseBody = response.getBody();
        
        // Log del resultado
        gs.info('HTTP Status: ' + httpStatus);
        gs.info('Response Body: ' + responseBody);
    } else {
        gs.error('No se pudo encontrar el archivo con sys_id: ' + attachmentSysId);
    }
} catch (ex) {
    gs.error('Error al enviar el archivo: ' + ex.message);
}

example_console_test.png

0 REPLIES 0