Implement a Logo Upload functionality on Home, PLP and PDP pages. Using the functionality the users can upload their logo image from the device to the website.
The uploaded logo need to be stored locally in non-logged case and to the customer record in logged in case


Entry point file
define(
'Vserve.Virtual_Sampling.Uploadlogo'
, [
'Vserve.Virtual_Sampling.Uploadlogo.View'
]
, function (
UploadlogoView
)
{
'use strict';
return {
mountToApp: function mountToApp (container)
{
// using the 'Layout' component we add a new child view inside the 'Header' existing view
// (there will be a DOM element with the HTML attribute data-view="Header.Logo")
// more documentation of the Extensibility API in
// https://system.netsuite.com/help/helpcenter/en_US/APIs/SuiteCommerce/Extensibility/Frontend/index.html
/** @type {LayoutComponent} */
var layout = container.getComponent('Layout');
if(layout)
{
layout.addChildView('Logo-upload-view', function() {
return new UploadlogoView({ container: container });
});
}
}
};
});
view file
// @module Vserve.Virtual_Sampling.Uploadlogo
define('Vserve.Virtual_Sampling.Uploadlogo.View'
, [
'vserve_virtual_sampling_uploadlogo.tpl'
, 'Vserve.Virtual_Sampling.Uploadlogo.Model'
, 'Backbone', 'Utils', 'Configuration', 'Profile.Model'
]
, function (
vserve_virtual_sampling_uploadlogo_tpl
, VserveVirtual_SamplingUploadlogoModel
, Backbone, Utils, Configuration, ProfileModel
) {
'use strict';
// @class Vserve.Virtual_Sampling.Uploadlogo.View @extends Backbone.View
return Backbone.View.extend({
template: vserve_virtual_sampling_uploadlogo_tpl
, initialize: function (options) {
/* Uncomment to test backend communication with an example service
(you'll need to deploy and activate the extension first)
*/
this.model = new VserveVirtual_SamplingUploadlogoModel();
var isLoggedIn = ProfileModel.ProfileModel ? ProfileModel.ProfileModel.getInstance().get('isLoggedIn')
: ProfileModel.getInstance().get('isLoggedIn');
if (isLoggedIn) {
var self = this;
var Customerid = ProfileModel.getInstance().get('internalid');
var url = Utils.getAbsoluteUrl(getExtensionAssetsPath("services/Uploadlogo.Service.ss"))
$.get(url, { data: JSON.stringify(Customerid) })
.done(function (data) {
var imageurl = JSON.parse(data.imageurl).code.url;
self.imageurlFromRec = imageurl;
self.render();
})
}
// var self = this;
// this.model.fetch().done(function(result) {
// console.log("result",JSON.stringify(result))
// self.message = result.message;
// self.render();
// });
}
, events: {
'click [data-action="open-gallery"]': "OpenGallery",
'click [data-action="UploadButton"]': "UploadButton",
'change [data-action="UploadFile"]': 'UploadFile',
'click [data-action="Remove-background"]': "RemoveBg",
}
, RemoveBg: function RemoveBg() {
var self = this;
var checkValue = document.getElementById("removebg").checked ? 1 : 0;
var useimgurl = self.imageurlFromRec
var imgwithBg = localStorage.getItem('mtlFileContent') ? localStorage.getItem('mtlFileContent') : useimgurl;
console.log("imgwithBg", imgwithBg);
if (localStorage.getItem('mtlFileContent')) {
var fileformat = imgwithBg.split(";")[0].split(":")[0];
console.log("fileformat", fileformat);
}
var imgwithOutBg = localStorage.getItem('noBGimgurl');
if (checkValue == 1) {
if (fileformat && fileformat == "image/gif" || fileformat == "image/svg+xml") {
document.getElementById("bgremoval_errormessage").innerHTML = "Only JPG and PNG images are supported."
} else {
document.getElementById('imageid').id = 'loader';
setTimeout(function () {
document.getElementById('loader').id = 'imageid';
}, 5000);
setTimeout(function () {
$("#imageid").attr("src", imgwithOutBg);
}, 5000);
}
} else {
document.getElementById("bgremoval_errormessage").innerHTML = ""
$("#imageid").attr("src", imgwithBg);
}
}
, OpenGallery: function OpenGallery() {
$("#MyPopup").modal("show");
var isimgexist = $("#uploadimg").find("img").length < 1;
if (isimgexist) {
document.getElementById("bgremovalcheckbox").style.display = "none";
} else {
document.getElementById("bgremovalcheckbox").style.display = "block";
}
}
, UploadButton: function () {
$('#mtlFileInput').click();
}
, UploadFile: function (e) {
var self = this;
var mtlFileContent = '';
var imagefiletype = '';
document.getElementById("removebg") ? document.getElementById("removebg").checked = 0 : "";
var mtlFile = document.getElementById('mtlFileInput').files[0];
var size = document.getElementById('mtlFileInput').files[0].size;
var filetype = document.getElementById('mtlFileInput').files[0].type;
//console.log("mtlFile=" , mtlFile);
//this.mtlFile = mtlFile
var readerMTL = new FileReader();
if (filetype != "image/png" && filetype != "image/svg+xml" && filetype != "image/jpeg" && filetype != "image/jpg" && filetype != "image/gif") {
document.getElementById("fileformat_errormessage").innerHTML = "FAILED - Unsupported format. Please upload supported file format."
}
else if (size > 4000000) {
document.getElementById("filesize_errormessage").innerHTML = "File size exeeds 4 MB! Please upload file with size less than 4 MB! ";
}
else {
document.getElementById("filesize_errormessage").innerHTML = ""
document.getElementById("fileformat_errormessage").innerHTML = ""
readerMTL.onload = (function (reader) {
return function () {
mtlFileContent = reader.result;
mtlFileContent = mtlFileContent.replace('data:;base64,', '');
var apiKey = Configuration.get("logouploadsubtab.bgremovalapikey");
console.log("apiKey", apiKey);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 800;
var canvas = document.createElement('canvas');
var imgData = mtlFileContent;
var img = new Image();
img.onload = function () {
var width = img.width;
var height = img.height;
console.log("widthandheight", width + "X" + height)
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL(filetype);
localStorage.setItem('mtlFileContent', dataurl);
return dataurl;
}
img.src = imgData;
setTimeout(function () {
var myHeaders = new Headers();
myHeaders.append("X-Api-Key", apiKey);
myHeaders.append("Accept", "application/json");
var formdata = new FormData();
formdata.append("size", "full");
formdata.append("image_file_b64", localStorage.getItem('mtlFileContent'))
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("https://api.remove.bg/v1.0/removebg", requestOptions)
.then((response) => response.json())
.then(function (response) {
console.log("result1", response);
var base64withnobg = response.data.result_b64;
var noBGimgurl = localStorage.getItem('mtlFileContent').split(",")[0] + ',' + base64withnobg;
localStorage.setItem('noBGimgurl', noBGimgurl);
console.log("noBgimg", noBGimgurl)
})
.catch(error => console.log('error', error));
}, 500);
//localStorage.setItem('mtlFileContent', mtlFileContent);
var isimage = $("#uploadimg").find("img").length < 1;
var isLoggedIn = ProfileModel.ProfileModel ? ProfileModel.ProfileModel.getInstance().get('isLoggedIn')
: ProfileModel.getInstance().get('isLoggedIn')
if (isimage) {
setTimeout(function () {
var img = $('<img id="imageid">');
img.attr('src', localStorage.getItem('mtlFileContent'));
img.appendTo('#uploadimg');
document.getElementById("bgremovalcheckbox").style.display = "block";
}, 1500);
} else {
setTimeout(function () {
$("#imageid").attr("src", localStorage.getItem('mtlFileContent'));
document.getElementById("bgremovalcheckbox").style.display = "block";
}, 1500);
}
if (filetype == "image/png") { imagefiletype = 'PNGIMAGE' }
else if (filetype == "image/jpg") { imagefiletype = 'JPGIMAGE' }
else if (filetype == "image/jpeg") { imagefiletype = 'JPGIMAGE' }
else if (filetype == "image/svg+xml") { imagefiletype = 'SVGIMAGE' }
else if (filetype == "image/gif") { imagefiletype = 'GIFIMAGE' }
setTimeout(function () {
var resizeimage = localStorage.getItem('mtlFileContent');
var b64resizimg = resizeimage.split("base64,")[1];
var object = {
base64: b64resizimg,
imagefiletype: imagefiletype
}
if (isLoggedIn) {
var url = Utils.getAbsoluteUrl(
getExtensionAssetsPath(
"services/Uploadlogo.Service.ss"))
$.post(url, JSON.stringify(object))
}
}, 500);
}
})(readerMTL);
readerMTL.readAsDataURL(mtlFile);
}
}
, bindings: {
}
, childViews: {
}
//@method getContext @return Vserve.Virtual_Sampling.Uploadlogo.View.Context
, getContext: function getContext() {
var self = this;
var imageurlFromRec;
var isLoggedIn = ProfileModel.ProfileModel ? ProfileModel.ProfileModel.getInstance().get('isLoggedIn')
: ProfileModel.getInstance().get('isLoggedIn');
if (isLoggedIn) {
imageurlFromRec = self.imageurlFromRec ? self.imageurlFromRec : "";
//console.log("imageurlFromRec",'https://1072230-sb1.app.netsuite.com' + imageurlFromRec)
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
resolve(base64data);
}
});
}
getBase64FromUrl(imageurlFromRec)
.then(function (response) {
self.userimgUrl = response;
})
setTimeout(function () {
var userimgUrl = self.userimgUrl;
var apiKey = Configuration.get("logouploadsubtab.bgremovalapikey");
var myHeaders = new Headers();
myHeaders.append("X-Api-Key", apiKey);
myHeaders.append("Accept", "application/json");
var formdata = new FormData();
formdata.append("size", "auto");
formdata.append("image_file_b64", userimgUrl)
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("https://api.remove.bg/v1.0/removebg", requestOptions)
.then((response) => response.json())
.then(function (response) {
var base64withnobg = response.data.result_b64;
var noBGimgurl = userimgUrl.split(",")[0] + ',' + base64withnobg;
localStorage.setItem('noBGimgurl', noBGimgurl);
})
.catch(error => console.log('error', error));
}, 1500);
}
var urlfromcookie = localStorage.getItem('mtlFileContent');
var UploadButtonImg = Configuration.get("logouploadsubtab.uploadbuttonimage");
//console.log("thisss",this)
return {
urlfromcookie: urlfromcookie ? urlfromcookie : imageurlFromRec,
UploadButtonImg: UploadButtonImg
};
}
});
});
Template file
<div class="logo-upload-utility">
<input type="image" src="{{UploadButtonImg}}" name="UploadButton"
id="LogoUpload" data-action="open-gallery">
</div>
<div id="MyPopup" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<div class="heading"> <h4 class="modal-title">{{translate "Your Logo & Designs Gallery"}}</h4></div>
<div class="close-button"> <button type="button" class="close" data-dismiss="modal">x</button></div>
</div>
<div id="uploadimg">
{{#if urlfromcookie}}<img id="imageid" src="{{urlfromcookie}}" />{{/if}}
</div>
<div id="bgremoval_errormessage"></div>
<div id="bgremovalcheckbox">
<input type="checkbox" name="same-as-address" value="1" id="removebg" data-action="Remove-background">{{translate "Remove Background"}}</input>
</div>
<div class="logo-upload-info"><p>{{translate "Click to Upload and change to see your logo on products"}}</p></div>
<div id="filesize_errormessage"></div>
<div id="fileformat_errormessage"></div>
<div class="file-input">
<div class="new_upload_Btn" data-action="UploadButton">{{translate "Upload Your Logo"}}</div>
<input class="FullWidth" type="file" name="mtlFileInput" value="" id="mtlFileInput"
data-action="UploadFile">
</div>
<div class="logo-upload-fileformat"> <p>{{translate "Recommended formats : PNG, JPG, JPEG, SVG, GIF"}}</p></div>
<div class="logo-upload-filesize"> <p>{{translate "Max. file size: 4MB"}}</p></div>
<div class="modal-footer">
<button type="button" class="closebutton" data-dismiss="modal">
{{translate "Close"}}</button>
</div>
</div>
</div>
</div>
Suitescript files
ServiceController file
define("Vserve.Virtual_Sampling.Uploadlogo.ServiceController", ["ServiceController","Vserve.Virtual_Sampling.Uploadlogo"], function(
ServiceController, VserveVirtual_SamplingUploadlogo
) {
"use strict";
console.error("inside servicecontroller")
return ServiceController.extend({
name: "Vserve.Virtual_Sampling.Uploadlogo.ServiceController",
// The values in this object are the validation needed for the current service.
options: {
common: {}
},
get: function get() {
try{
var data = this.request.getParameter('data');
var data = VserveVirtual_SamplingUploadlogo.getUrlFromRec(data);
return data;
} catch(e){
console.error('error at controllerget2', e);
}
},
post: function post() {
try{
var data = this.data;
var data = VserveVirtual_SamplingUploadlogo.getUrl(data);
return data;
}
catch(e){
console.error('error at controllerget', e);
}
},
put: function put() {
// not implemented
},
delete: function() {
// not implemented
}
});
});
model file
// Vserve.Virtual_Sampling.Uploadlogo.js
// Load all your starter dependencies in backend for your extension here
// ----------------
define('Vserve.Virtual_Sampling.Uploadlogo'
, [
'Vserve.Virtual_Sampling.Uploadlogo.ServiceController','SC.Model'
]
, function (
UploadlogoServiceController,SCModel
)
{
'use strict';
console.error("test34");
return SCModel.extend(
{
getUrl: function (data){
try{
var objects = data
var file = objects.base64;
var filetype = objects.imagefiletype;
var customerId = nlapiGetContext().getUser();
var filename = customerId + '_logo';
var url = nlapiResolveURL('SUITELET', 'customscript_myronuploadlogo', 'customdeploy1', true);
var postdata = {
base64: file,
filetype: filetype,
filename: filename,
customerId: customerId,
};
var response = nlapiRequestURL(url, postdata, null, "POST");
var body = response.getBody();
console.error("body", body)
var URLParsed = JSON.parse(body);
console.error("URLParsed", URLParsed)
var responseCode = parseInt(response.getCode(), 10);
console.error("responseCode", responseCode)
if (responseCode === 200 || responseCode === 302 || responseCode === 201 || responseCode === 404) {
return {
imageurl: body
}
}
}catch(e){
console.error('error at model', e);
}},
getUrlFromRec: function(){
try{
var customerId = nlapiGetContext().getUser();
var FileName = customerId + '_logo';
var url = nlapiResolveURL('SUITELET', 'customscript_myronuploadlogo', 'customdeploy1', true);
var postdata = {
FileName: FileName,
WhenPageload: true,
};
var response = nlapiRequestURL(url, postdata, null, "POST");
var body = response.getBody();
console.error("body2", body)
var URLParsed = JSON.parse(body);
console.error("URLParsed", URLParsed)
var responseCode = parseInt(response.getCode(), 10);
console.error("responseCode", responseCode)
if (responseCode === 200 || responseCode === 302 || responseCode === 201 || responseCode === 404) {
return {
imageurl: body
}
}
}catch(e){
console.error('error at model2', e);
}
}
})
});