How to Utilize a File Input Field on a Form in SuiteCommerce

When implementing or further customizing your SuiteCommerce site, you might find yourself wanting to add a file input field on a SuiteCommerce form. However, getting the files into NetSuite can be tricky. The code below walks you through the front-end and back-end code needed to add this file upload field to your SuiteCommerce form.

Front End Code

In your front-end view, add an event listener function for file input fields:

events: {
    'change input[type="file"]': "handleFileAdd",
},
/**
  * Validate and format the file added.
  * @param {Event Object} event
*/
handleFileAdd: function (event) {
    //remove an error message attached to the file field if it exists
    let fieldError = $(`#my-file-input-error`);
    !!fieldError.length && fieldError.remove();
    //do nothing if there are no "file(s)" in the event object
    if (!(event.target && event.target.files && event.target.files[0])) return;
    let file = event.target.files[0];
    //ensure the file is smaller than some pre-determined size limit
    if (file.size > 1000 * 1000 * 10) {
        //add an error message if the file is too big
        $(event.target).after(
            `<p data-validation-error="block" id="${this.model.get(
                "fieldId"
            )}-error">
            The selected file is too large. The maximum file size is 10 megabytes (MB).</p>`
        );
    } 
    //format the file data for the https request
    else {
        //declare a file reader object
        const reader = new FileReader();
        //add listener for the reader
        reader.addEventListener(
            "load",
            () => {
                //save the formatted file data (base64 encrypted) to your model
                this.model.set("fileData", {
                    name: file.name,
                    type: file.type,
                    data: reader.result.split(",")[1], //this is needed to remove some metadata off the front of the encrypted string
                });
            },
            false
        );
        //trigger the reader listerer function and pass it the file
        reader.readAsDataURL(file);
    }
},

The above listener will validate and format your data so that it is ready to send to a backend service file.

Even after doing the above, you will likely need to overwrite the form submission function to ensure your file data is sent correctly to the backend.

Back End Code

Assuming your code correctly passed the file data to your service file, you can convert that data to a file and save it to the file. cabinet as follows:

/**
* Add file to file cabinet.
* @param {Object} fileToAdd: based on an object matching the earlier code snippet
*/
function addFile (fileToAdd) {
    try {
        // this file type map maps the incoming file type data to the file module
        // Type ENUM. The mapping does NOT cover all potential file types. 
        let fileTypeMap = {
            "text/csv": file.Type.CSV,
            "application/vnd.ms-excel": file.Type.EXCEL,
            "text/javascript": file.Type.JAVASCRIPT,
            "image/jpeg": file.Type.JPGIMAGE,
            "application/json": file.Type.JSON,
            "application/ld+json": file.Type.JSON,
            "video/mp4": file.Type.MPEGMOVIE,
            "video/mpeg": file.Type.MPEGMOVIE,
            "audio/mp3": file.Type.MP3,
            "application/pdf": file.Type.PDF,
            "text/plain": file.Type.PLAINTEXT,
            "image/png": file.Type.PNGIMAGE,
            "application/vnd.ms-powerpoint": file.Type.POWERPOINT,
            "application/vnd.ms-powerpoint": file.Type.POWERPOINT,
            "image/svg+xml": file.Type.SVG,
            "image/tiff": file.Type.TIFFIMAGE,
            "application/msword": file.Type.WORD,
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                file.Type.WORD,
            "application/xml": file.Type.XMLDOC,
            "application/zip": file.Type.ZIP,
            "application/x-7z-compressed": file.Type.ZIP,
        };
        //use the file module to create a file
        let fileObj = file.create({
            name: fileToAdd.name,
            fileType: fileTypeMap[fileToAdd.type],
            contents: fileToAdd.data,
            description: "Describe your file",
            encoding: file.Encoding.UTF8,
            folder: -20, //User Documents or whatever folder you want
        });
        //save your file
        let fileId = fileObj.save();
    } catch (error) {
        log.error("addFile error", error);
    }
},

Your file is now saved to the file cabinet and can be attached to records as needed!

Author: Sam Gagliardi


Got stuck on a step in this article?

We like to update our blogs and articles to make sure they help resolve any troubleshooting difficulties you are having. Sometimes, there is a related feature to enable or a field to fill out that we miss during the instructions. If this article didn't resolve the issue, please use the chat and let us know so that we can update this article!


Oracle NetSuite Alliance Partner & Commerce Partner

If you have general questions about SuiteCommerce or more specific questions about how our team can support your business as you implement NetSuite or SuiteCommerce, feel free to contact us anytime. Anchor Group is a certified Oracle NetSuite Alliance Partner and Commerce Partner equipped to handle all kinds of NetSuite and SuiteCommerce projects, large or small!

We are a premium SuiteCommerce agency that creates powerful customer portals. Unlike our competitors, we have already solved your problems.

 
 

Want to keep learning?

Our team of NetSuite professionals has written articles on a wide variety of NetSuite topics, from SuiteCommerce tips, to recommended NetSuite solutions, to available support services, and more! 

Your cart