Sunday, August 2, 2015

Upload file with ajax - Liferay

In developer life, to stuck at any point is routine. here is one of the point i am sharing where many of us stuck and it's take lot more times to come out with solution.


Scenario: upload file with Ajax.
Some time we need to upload(by file) some data and process them. but after finished data process page doesn't refreshed. to achieve this we defiantly use Ajax. so, generally we giving <portlet:resourceURL> in form action. form which include input file object. here in this case, if we submit the form and try to get uploaded file in liferay controller. it's doesn't work because of ajax. your serverResource() of  portlet controller is not able to fetch file object from request. because ajax request generally we are passing String & Number data. but this is File so ajax can not handle this tyep of data. after trying more and giving lot more time to resolve this. i found resolution that what i am going to share here....

Here is what you need to do... 

1) JSP contains input-file (With or Without Form)  

<script type="text/javascript" src="/XYZ-porlet/js/ajaxfileupload.js"></script>

  

<portlet:resourceURL var="fileImportURL" id="fileImport"></portlet:resourceURL>

 

<input id="fileUpload" name="file" type="file"  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"/>

 

 <input type="button" name="upload" id="upload" value="Upload" onclick="ajaxFileUpload()" />


2) Write JS for AJAX

function ajaxFileUpload(){

$.ajaxFileUpload
    ({
        secureuri : false,
        fileElementId : 'fileUpload',
        data: {name: 'Ketan'},
        url: '<%=fileImportURL%>',
        success: function (data, status)
        {

                 alert("File upload success")
         },
        error: function (data, status, e) {

            alert("File upload faile");
        }
    })
 

   return false;

}

 

3) serveResource() of Liferay Controller

UploadPortletRequest uploadRequest   =  PortalUtil.getUploadPortletRequest(resourceRequest);
File file = uploadRequest.getFile("
fileUpload");

 

 

That's all enough to do for ajax file upload. Enjoy!!

 

 

Click Here to download required js file.