1

I'm here to tell you about a problem I'm having and what I think should work is not working for me.

The main problem is that I am integrating Salesforce with a new document manager. The administrators of the document manager have told me that due to performance problems the files can no longer be sent in base64 so we have to use Blob.

In my organization we have developed many visual pages from which documents are uploaded and these documents travel directly to the document manager.

I have changed the treatment of files uploaded through the button so that Base 64 is transformed to Blob as follows:

var ALF_AddDocument = function() {
    // ALFRESCO_GD: Pruebas

    var base64String = 'JVBERi0xLjcNCiW1tbW1DQoxIDAgb2JqDQo8PC9.....';

    // Decodificar la cadena base64 a un ArrayBuffer
    function base64ToArrayBuffer(base64) {
        var binaryString = atob(base64);
        var len = binaryString.length;
        var bytes = new Uint8Array(len);
        for (var i = 0; i < len; ++i) {
            bytes[i] = binaryString.charCodeAt(i);
        }
        return bytes.buffer;
    }

    // Crear un Blob a partir del ArrayBuffer
    function arrayBufferToBlob(buffer, type) {
        return new Blob([buffer], { type: type });
    }

    // Decodificar la cadena base64
    var arrayBuffer = base64ToArrayBuffer(base64String);

    // Crear el Blob
    var blob = arrayBufferToBlob(arrayBuffer, 'application/pdf');

    var reader = new FileReader();
    var binaryString;

    reader.onloadend = function(event) {
        DocumentoController.ALF_AddDocument(blob, function(result, event) {
            if (event.status) {
                console.log('Éxito');
            } else {
                // Manejar errores si la llamada al método remoto falla
                console.error('Error: ' + event.message);
            }
        });
    };

    reader.readAsBinaryString(blob);

    // Crear una URL para el Blob
    var url = URL.createObjectURL(blob);
    console.log('url');
    console.log(url);

    // Abrir una nueva ventana del navegador con el PDF
    window.open(url, '_blank');
};

The window.open is to check that the blob has the correct encoding and so it is, I can see the original pdf without problem. Once that is done, the optimal thing would be to send that same blob to my controller and from there send it to another apex from where I make the http request to the document manager server using a form data:

// Crear una instancia de HttpRequest
        HttpRequest req = new HttpRequest();
        req.setEndpoint(Endpoint);
        req.setMethod('POST');
        req.setTimeout(120000); // milisegundos
        // Crear el cuerpo de la solicitud
        String boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';
        String body = '--' + boundary + '\r\n';
        body += 'Content-Disposition: form-data; name="content"; filename="archivo.pdf"\r\n';
        body += 'Content-Type: application/octet-stream\r\n\r\n';
        body +=  fileblob + '\r\n'; // Adjunta el contenido del archivo
        body += '--' + boundary + '\r\n';
        body += 'Content-Disposition: form-data; name="data"\r\n\r\n';
        body += dataText + '\r\n'; // Texto para el campo data
        body += '--' + boundary + '\r\n';
        body += 'Content-Disposition: form-data; name="dataExp"\r\n\r\n';
        body += dataexText + '\r\n'; // Texto para el campo dataex
        body += '--' + boundary + '--\r\n';
        system.debug('body');
        system.debug(body);
        // Establecer el cuerpo de la solicitud y el encabezado Content-Type
        req.setBody(body);
        req.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);

        // Instancia de HTTP
        Http http = new Http();

        // Enviar la solicitud y obtener la respuesta
        HttpResponse res = http.send(req);

I think this is not possible. Do you know if there is any way?

What I have done is send the string in base64 and in apex do this:

       Blob fileBlob = EncodingUtil.base64Decode(content);
 

The problem is that when I send that blob to the manager, it does not interpret it correctly and instead of the file being output in KB it is output in bytes and does not allow it to be opened.

Does anything occur to you? If you need more detail about something, say so.

Thanks in advance.

4
  • In Apex, Strings are UTF-8. This means you can't naively just do blob += fileblob, because it will be passed through Object.toString(), and you just end up with Blob[bytes] as the output (where bytes is the size of the blob). Instead, you need to transform it into base64 or hex, and build the entire payload that way, then convert it to a blob before sending. See this Q&A as an example.
    – sfdcfox
    Commented May 25 at 13:05
  • Hi, thanks for your response. I haven't mentioned it but I also tried the following: reader.readAsBinaryString(blob); binaryString = reader.result; And I sent that binaryString to the apex to make the call, the result was very curious and the PDF was downloaded and opened perfectly with the correct number of pages, but completely BLANK lol
    – Banzoni
    Commented May 25 at 14:30
  • 1
    My guess is that some string handling truncated the string at the first NUL (0x00) character, enough to get the PDF header, but not the contents. You should definitely use base64 encoding from client to server, and then use the blob-building technique noted in the Q&A I linked earlier.
    – sfdcfox
    Commented May 25 at 14:38
  • The problem is that I get the Blob in the visualforce and I make the call from APEX. If you notice, I am already using the formdata sending format that is mentioned in your post. What I need is a way to get the blob from the visual into the apex. If I transform the blob into base64 in the visual, I pass it to apex and in apex I transform it into a blob again, the object is not generated but something like "Blob[23231]"
    – Banzoni
    Commented May 27 at 7:42

0

You must log in to answer this question.

Browse other questions tagged .