Thursday, November 29, 2018

Use RESTlet to upload an image to File Cabinet

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 upload an image to the File Cabinet.

We can convert the image file into a base64 encoded string, and pass the details as json object or plain text. Note that NetSuite has an API that can automatically convert the base64 encoded string back to image (JPEG). This is quite useful if we are building mobile application that would take picture and at the same time be able to upload it to NetSuite. 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:


            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[]));
            try
            {
                img = Convert.ToBase64String(imageByteArray);
    
            }
            catch { }
        
            string jsonString = "{\"tranid\":\"200\", \"rImage\":\"" + img + "\"" + "}";
         
            WebRequest request = WebRequest.Create("https://rest.netsuite.com/app/site/hosting/restlet.nl?script=489&deploy=1");
            request.ContentType = "application/json";
            request.Method = "POST";
            request.Headers.Add("Authorization:NLAuth nlauth_account=TSTDRV780XXX,nlauth_email=XXXX@netsuite.com,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 saveThisFile(data){

var imgB64= data.rImage;

//you just need to dynamically name your file
var newImg = nlapiCreateFile('rImage5.jpg', 'JPGIMAGE', imgB64);
newImg.setFolder(9); //set the folder here
var id2=nlapiSubmitFile(newImg);

return "test";
}

 


 

 

1 comment:

  1. It throw error : The remote server returned an error: (403) Forbidden.

    ReplyDelete