Thursday, 22 November 2018

Drag and Drop Scenario

Step 1 :

<div class="dradDropDiv"> <input type="hidden" id="finalFileList" name=" <portlet:namespace />finalFileList" /> <div> <span class="dragbtnGipSingle fileinput-button"> <div class="row"> <br> <div class="col-sm-1"></div> <div class="col-sm-3"> <img alt='File Upload Image' width='75' height='75' name="fileUploadImage" id="fileUploadImage" class="fileUploadImage" src="${renderRequest.getContextPath()}/images/arrow-upload-up-document-file-.png"> </div> <div class="col-sm-8" style="margin-top: 15px"> <div> <font size="3">Drag-Drop Documents Here</font> </div> <div> Or <font size="4" color="blue">Click to Browse</font> </div> </div> </div> <input type="file" name="files[]" id="files" multiple accept=".xls,.xlsx,.jpg,.png,.gif,.pdf,.docx"> <br /> <input type="hidden" id="newFileList" name="finalFileList" /> </span> <output id="Filelist"></output> <div style="clear: both;"></div> <br /> </div> <div class="noticeFilesTable" style="margin-left: 10%"> <table id="fileDisplay" class="display table-display dataTable no-footer" style="width:450px"> <thead> <tr> <th align="left" bgcolor="#ddd">File Name</th> <th align="left" bgcolor="#ddd" colspan="2">Size</th> </tr> </thead> <tbody id="tempTableBody"></tbody> </table> </div> </div>


Step 2 :

.dradDropDiv div { float: left; clear: none; }
 .dragbtnGipSingle {
     display: inline-block;
     width: 420px;
     height: 130px;
     padding: 6px 12px;
     margin-bottom: 0;
     font-size: 14px;
     font-weight: normal;
     line-height: 1.42857143;
     text-align: center;
     white-space: nowrap;
     vertical-align: middle;
     cursor: pointer;
     -webkit-user-select: none;
     -moz-user-select: none;
     -ms-user-select: none;
     user-select: none;
     background-image: none;
     border: 1px solid #0B85A1;
     border-radius: 4px;
}
.fileinput-button {
     position: relative;
     overflow: hidden;
}
 .fileinput-button input {
     position: absolute;
     top: 0;
     right: 0;
     margin: 0;
     opacity: 0;
     -ms-filter: 'alpha(opacity=0)';
     font-size: 200px;
     direction: ltr;
     cursor: pointer;
}

Step 3 : 
//I added event handler for the file upload control to access the files properties.
document.addEventListener("DOMContentLoaded", init, false);
//To save an array of attachments 
var AttachmentArray = [];
//counter for attachment array
var arrCounter = 0;
//to make sure the error message for number of files will be shown only one time.
var filesCounterAlertStatus = false;
function init() {

    //add javascript handlers for the file upload event
    document.querySelector('#files').addEventListener('change', handleFileSelect, false);
}

    //the handler for file upload event
    function handleFileSelect(e) {
    //to make sure the user select file/files
        if (!e.target.files) return;

        //To obtaine a File reference
        var files = e.target.files;
            // Loop through the FileList and then to render image files as thumbnails.
            for (var i = 0, f; f = files[i]; i++) {

                //instantiate a FileReader object to read its contents into memory
                var fileReader = new FileReader();
                // Closure to capture the file information and apply validation.
                fileReader.onload = (function (readerEvt) {
                    return function (e) {
                        
                        //Apply the validation rules for attachments upload
                        ApplyFileValidationRules(readerEvt)

                        //Render attachments thumbnails.
                        RenderThumbnail(e, readerEvt);

                        //Fill the array of attachment
                        FillAttachmentArray(e, readerEvt)
                    };
                })(f);

                // Read in the image file as a data URL.
                fileReader.readAsDataURL(f);
            }
            document.getElementById('files').addEventListener('change', handleFileSelect, false);
    }

    //To remove attachment once user click on x button
    jQuery(function ($) {
        $('div').on('click', '.img-wrap .close', function () {
            var id = $(this).closest('.img-wrap').find('img').data('id');

            //to remove the deleted item from array
            var elementPos = AttachmentArray.map(function (x) { return x.FileName; }).indexOf(id);
            if (elementPos !== -1) {
                AttachmentArray.splice(elementPos, 1);
            }
            //to remove div tag that contain the image
            $(this).parent().find('div').not().remove();

            //to remove div tag that contain caption name
            $(this).parent().parent().find('div').not().remove();
        });
    });

    //Apply the validation rules for attachments upload
    function ApplyFileValidationRules(readerEvt)
    {
        //To check file type according to upload conditions
        if (CheckFileType(readerEvt.type) == false) {
            alert("The file (" + readerEvt.name + ") does not match the upload conditions, You can only upload jpg/png/gif files");
            e.preventDefault();
            return;
        }

        //To check file Size according to upload conditions
        if (CheckFileSize(readerEvt.size) == false) {
            alert("The file (" + readerEvt.name + ") does not match the upload conditions, The maximum file size for uploads should not exceed 300 KB");
            e.preventDefault();
            return;
        }

        //To check files count according to upload conditions
        if (CheckFilesCount(AttachmentArray) == false) {
            if (!filesCounterAlertStatus) {
                filesCounterAlertStatus = true;
                alert("You have added more than 10 files. According to upload conditions you can upload 10 files maximum");
            }
            e.preventDefault();
            return;
        }
    }

//To check file type according to upload conditions
    function CheckFileType(fileType) {
    /* 

        if (fileType == "image/jpeg") {
            return true;
        }
        else if (fileType == "image/png") {
            return true;
        }
        else if (fileType == "image/gif") {
            return true;
        }
        else {
            return false;
        }
        
*/
        return true;
    }
    
    // Converting Byte of KB and MB
function bytesToSize(bytes) {
  var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  if (bytes == 0) return '0 Byte';
  var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
  return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

    //To check file Size according to upload conditions
    function CheckFileSize(fileSize) {
        if (fileSize < 300000000) {
            return true;
        }
        else {
            return false;
        }
        return true;
    }

    //To check files count according to upload conditions
    function CheckFilesCount(AttachmentArray) {
        //Since AttachmentArray.length return the next available index in the array, 
        //I have used the loop to get the real length
        var len = 0;
        for (var i = 0; i < AttachmentArray.length; i++) {
            if (AttachmentArray[i] !== undefined) {
                len++;
            }
        }
        //To check the length does not exceed 10 files maximum
        if (len > 9) {
            return false;
        }
        else
        {
            return true;
        }
    }

function removeMe(ele){
var id = ele.className;

            //to remove the deleted item from array
            var elementPos = AttachmentArray.map(function (x) { return x.FileName; }).indexOf(id);
            if (elementPos !== -1) {
                AttachmentArray.splice(elementPos, 1);
            }
document.getElementById('fileDisplay').deleteRow(ele.parentNode.rowIndex);
arrCounter = arrCounter - 1;
}
    //Render attachments thumbnails.
    function RenderThumbnail(e, readerEvt)
    {
var name = readerEvt.name;
var markup = '<tr><td class="dt-body-left text-left">'+readerEvt.name+'</td><td  class="dt-body-left text-left">'+ bytesToSize(readerEvt.size)+'</td> <td class="'+readerEvt.name+' dt-body-left text-left" onclick="removeMe(this);"><span class="close dt-body-left text-left">' + "<img src='${renderRequest.contextPath}/images/delete_new.png' alt='delete' height='20' width='25'>" +'</span></td> </tr>';
$("table tbody#tempTableBody").append(markup);

//alert(JSON.stringify(AttachmentArray));
      
    }

    //Fill the array of attachment
    function FillAttachmentArray(e, readerEvt)
    {
    
        AttachmentArray[arrCounter] =
        {
            FileName: readerEvt.name,
            MimeType: readerEvt.type,
            Content: e.target.result.split("base64,")[1],
            FileSizeInBytes: readerEvt.size,
        };
        arrCounter = arrCounter + 1;
    }

Step 3: 
document.getElementById("finalFileList").value = JSON.stringify(AttachmentArray);
  var myAttachmentArray = document.getElementById("finalFileList").value;

send this using ajax call to controller 

Step 4 : 

String fileJsonString = ParamUtil.getString(resourceRequest, "myAttachmentArray");
JSONArray caseDocJsonArray = JSONFactoryUtil.createJSONArray(fileJsonString);
for (int index = 0; index < caseDocJsonArray.length(); index++) {
JSONObject caseDocJsonObject = caseDocJsonArray.getJSONObject(index);
byte[] data = Base64.decode(editArrayObject.getString("content"));
if (data != null) {
try (OutputStream stream = new FileOutputStream("your path" + File.separator
+ editArrayObject.getString("FileName"))) {
stream.write(data);
}
} else {
}
}


Wednesday, 21 November 2018

Upload file in folder using ajax

Step1 :


<div>Choose Serial Number File</div>
<aui:input type="file" label="" name="serialNumbers[]" id="serialNumbers" cssClass="serialNumbers" multiple="true" accept=".csv"/>



Step 2 :


        var serialNumberfilenames='';
        var serialNumberAttachmentArray = [];
        var serialNumberCounter = 0 ;
    $("#<portlet:namespace/>serialNumbers").change(function (e) {
    serialNumberfilenames='';
    serialNumberAttachmentArray = [];
    serialNumberCounter = 0 ;
    //console.log(this.files.length);
    for (var i = 0; i < this.files.length; i++) {
    serialNumberfilenames +=   this.files[i].name + ',';
            }
    serialNumberfilenames = serialNumberfilenames.substr(0 , serialNumberfilenames.length-1);
    document.getElementById("serialNumberFilesNames").innerHTML = serialNumberfilenames;
        var files = e.target.files;
      for (var i = 0, f; f = files[i]; i++) {
        var fileReader = new FileReader();
                // Closure to capture the file information and apply validation.
                    fileReader.onload = (function (readerEvt) {
                        return function (e) {

                            //Fill the array of attachment
                            serialNumberAttachmentArray[serialNumberCounter] =
                              {
                                  FileName: readerEvt.name,
                                  MimeType: readerEvt.type,
                                  Content: e.target.result.split("base64,")[1],
                                  FileSizeInBytes: readerEvt.size,
                              };
                          serialNumberCounter = serialNumberCounter + 1;
                        };
                    })(f);
                    // Read in the image file as a data URL.
                    fileReader.readAsDataURL(f);
   


Step 3 :


<aui:button type="button" name="btnSubmitGip" id="btnSubmitGip" value="Submit" onClick="javascript:createNewGipCase()" ></aui:button>


Step 4 : 

function createNewGipCase(){
  

var productTableJsonString = JSON.stringify(serialNumberAttachmentArray);
AUI().use('aui-io-request', function(A){
            A.io.request('<%=saveRecord.toString()%>', {
                method: 'POST',
                dataType : "json",
                data: {

<portlet:namespace />productTableJsonString: productTableJsonString
}
})
})


}


STEP 5:

<portlet:resourceURL id="SAVE_RECORD" var="saveRecord"/>

var saveRecord = '<%=HtmlUtil.escapeJS(saveRecord.toString()) %>';



Step 6 :
In Serve resource get productTableJsonString 


JSONArray productTableJsonArray = JSONFactoryUtil.createJSONArray(productTableJsonString);
        for (int index = 0; index < productTableJsonArray.length(); index++) {

JSONObject editArrayObject = productTableJsonArray.getJSONObject(index);

byte[] data = Base64.decode(editArrayObject.getString("Content"));
if (data != null) {
try (OutputStream stream = new FileOutputStream(
"Pass folder Name here" + File.separator + editArrayObject.getString("FileName"))) {
stream.write(data);}else {

_log.info("Something went Wrong");
}
}

Tuesday, 20 November 2018

Drodown using ajax



STEP 1 : 
<aui:select id="region" name="region" label="" cssClass="regionDropdown">
<aui:option value="0" selected="selected">Region</aui:option>
</aui:select>

STEP2 : 
<script type="text/javascript">

window.addEventListener("load", onloadSingleRecord);

function onloadSingleRecord() {
populateAllDropdowns();
}

function populateAllDropdowns() {
var urlAction = "<%=retrieveDropdownListURL.toString()%>";
$.ajax({
      url: urlAction, 
      type: 'POST',
      dataType : "json",
      success: function(result){
      if(result["STATUS"] == "SUCCESS") {
          populateRegionDropdown(result["REGION_DROPDOWN"]);
      }
    }    
  });
}


STEP 3: 

<portlet:resourceURL id="LOAD_DROPDOWN_LIST" var="retrieveDropdownListURL" />
<script>
var retrieveDropdownListURL = '<%=HtmlUtil.escapeJS(retrieveDropdownListURL.toString()) %>';
</script>


STEP 4: 

@SuppressWarnings("static-access")
@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)throws IOException, PortletException {

String resourceId = resourceRequest.getResourceID();

if (null == resourceId || resourceId.isEmpty()) {
resourceResponse.setProperty(resourceResponse.HTTP_STATUS_CODE, "400");
resourceResponse.getWriter().write("This is not a valid request");
return;
}
if (resourceId.equals("LOAD_DROPDOWN_LIST")) {
fetchDropdownListUsingResource(resourceResponse);
} 



/* This is for Region drop down */
function populateRegionDropdown(resultData) {
if(resultData != null) {
var numberOfRows = resultData["REGION_DROPDOWN_ROWS"];
var dropDownObj = document.getElementById("<portlet:namespace/>region");
for(var rowCtr = 0; rowCtr < parseInt(numberOfRows); rowCtr++) {
var option_value = resultData[rowCtr]["RegionPK"] + '@@' + resultData[rowCtr]["RegionName"]
var newRow = new Option(resultData[rowCtr]["RegionName"], option_value);
dropDownObj.options[dropDownObj.length] = newRow;
}
}
}

STEP 5 : 

public static void fetchDropdownListUsingResource(ResourceResponse resourceResponse) throws IOException {
JSONObject json = null;
try {
json = JSONFactoryUtil.createJSONObject();
json.put("REGION_DROPDOWN", getRegionDropdownJSON());
json.put("STATUS", "SUCCESS");
resourceResponse.getWriter().write(json.toString());
resourceResponse.flushBuffer();
} catch (IOException e) {
json.put("STATUS", "FAILED");
resourceResponse.getWriter().write(json.toString());
resourceResponse.flushBuffer();
_log.error(e.getMessage());
}
}


STEP 6 : 

private static JSONObject getRegionDropdownJSON() {
JSONObject dropdownJson = JSONFactoryUtil.createJSONObject();
JSONObject rowData = null;

List<VwTcDropdownLists> listObj = VwTcDropdownListsLocalServiceUtil.getRegionDropDown();
if (listObj != null && (!listObj.isEmpty())) {
dropdownJson.put("REGION_DROPDOWN_ROWS", "" + listObj.size());
VwTcDropdownLists beanObj = null;
for (int i = 0; i < listObj.size(); i++) {
beanObj = listObj.get(i);
rowData = JSONFactoryUtil.createJSONObject();
rowData.put("RegionPK", "" + beanObj.getItemTreePosition());
rowData.put("RegionName", "" + beanObj.getItemName());
dropdownJson.put("" + i, rowData);
}
} else {
dropdownJson.put("REGION_DROPDOWN_ROWS", "" + 0);
}

return dropdownJson;
}