Thursday, November 29, 2018

Use RESTlet to attach an image or file to an existing record in NetSuite

Currently, the only supported input/output type for RESTlet are text/plain and application/json.

This article demonstrates how we could workaround with the current limitation and be able to attach an image or a NetSuite supported file type from an outside application to an existing record in NetSuite. This is very useful specially for an application that would like to automatically attach a taken image from a camera to a NetSuite record, be it a receipt for Expense report, a picture to be attached to an Opportunity record.

We can convert the image file into a base64 encoded string, and pass the details of the record as json object (record id, record type, image string). Note that NetSuite has an API that can automatically convert the base64 encoded string back to image (JPEG). Once file is created in NetSuite, we then use nlapiAttachRecord to attached the converted file to the specified record on the json object. Note that you can send other file types like PDF using the same process.

Below is a sample C# code that converts the image into base64 encoded string and passes the string to a RESTlet:     

            string img = string.Empty;
            System.Drawing.Image image1 = System.Drawing.Image.FromFile(@"C:\Documents and Settings\hhernandez\useNot.JPG");
            ImageConverter converter = new ImageConverter();
            Byte[] imageByteArray = (byte[]) converter.ConvertTo(image1, typeof(byte[]));
                img = Convert.ToBase64String(imageByteArray);                             
            string jsonString = "{\"tranid\":\"3187\", \"rectype\":\"customer\", \"rImage\":\"" + img + "\"" + "}";
            WebRequest request = WebRequest.Create("");
            request.ContentType = "application/json";
            request.Method = "POST";
            request.Headers.Add("Authorization:NLAuth nlauth_account=TSTDRV780XXX,,nlauth_signature=XXXX,nlauth_role=3");
            using (var streamWriter = new StreamWriter(request.GetRequestStream())) { streamWriter.Write(jsonString); }
            WebResponse response = request.GetResponse();

Below is the RESTlet that handles the POST request:

function saveItToCustomer(data){

var imgB64= data.rImage;

//dynamically name your file here
var newImg = nlapiCreateFile('rImage6.jpg', 'JPGIMAGE', imgB64);
newImg.setFolder(9);//set folder here
var id2=nlapiSubmitFile(newImg);

var type = data.rectype;   // the record type for the record being attached to
var id = data.tranid;  // this is the internal ID of the record

var attributes = null; 
nlapiAttachRecord('file', id2, type, id, attributes);

return "test";


No comments:

Post a Comment