Sunday 10 February 2013

File upload using serveResource() (AJAX call)

Objective : More oftenly we come across such requirements, when we need to do upload file using AJAX.(i.e. page must not be refreshed after upload).

Problem : we cannot directly upload by giving the <portlet:resourceURL> in jsp and then uploading in action class in serveResource() method, because UploadPortletRequest does not perform as is expected.

Introduction : For the same I found the solution of using ajaxfileupload.js
link : http://www.phpletter.com/DOWNLOAD/

Description :

in your jsp:

<portlet:resourceURL id="uploadMe" var="uploadMe" />



<form method="post" enctype="multipart/form-data" name="form" id=" ">
        <div class="popup_row2">
        <p><liferay-ui:message key="select_csv_file_to_upload_using_the_browse_button_then_click_upload" /></p>
           <div class="popup_row2_browse popup_add_bottomBtns" id="uploadFileDiv"> 
              <input type="file" name="fileToUpload" id="fileToUpload" value="Browse" class="input" required="required"/>
          </div>          
       </div>
       <div class="popup_row3">
        <p><liferay-ui:message key="csv_file_uploaded_successfully" /></p>
           <input type="button" name="upload" id="upload" value="Upload"  class="noText_shadow" onclick="uploadFileMe()" />
       </div>
 </form>

js functiom:


function uploadFileMe(){
$.ajaxFileUpload
(
{
url:'<%=uploadMe%>',
secureuri : false,
fileElementId : 'fileToUpload',
dataType : 'json',
data : {
name : 'logan',
id : 'id'
},
success : function(data, status) {
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
//alert(data.error);
} else {
//alert(data.msg);
}
}
},
error : function(data, status, e) {
//alert(e);
}
});


}

in your action class:


public void serveResource(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws PortletException, IOException {

try {
UploadPortletRequest uploadrequest = PortalUtil
.getUploadPortletRequest(resourceRequest);
InputStream inputStream = uploadrequest
.getFileAsStream("fileToUpload");
if(Validator.isNotNull(inputStream)){
File file = FileUtil.createTempFile(inputStream);
String uploadString = getFileAsString(file);

if (Validator.isNotNull(uploadString)) {

resourceResponse.getWriter().write( "validated_successfully");


LOGGER.info("VALIDATED_SUCCESSFULLY");
}else{
resourceResponse.getWriter().write( "failed");

LOGGER.info("VALIDATION_FAILED");
}
}
} catch (Exception e) {

LOGGER.error( "Error in adding modem");
}
}

public String getFileAsString(File file) {
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
StringBuffer sb = new StringBuffer();
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

while (dis.available() != 0) {
sb.append(dis.readLine() + "\n");
}
fis.close();
bis.close();
dis.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}



Conclusion: File can now be uploaded and validated on ajax call without refreshing the page.

8 comments:

  1. Good job.. Keep going!!

    ReplyDelete
  2. Hi Priyanka, Am new to liferay, Where should I put the js file in my project? Am using Liferay 6.1.1.

    ReplyDelete
  3. Hi priyanka, i too have got the same doubt karthik has. Pls help..

    ReplyDelete
  4. Hi, Please keep the js file in your portlet/docroot/js/ folder and make an entry in liferay-portlet.xml

    ReplyDelete
  5. its working .....but while we appending new upload browser dynamically via ajax call ..its not working....

    ReplyDelete
  6. Hi,
    Thanks for the tutorial. I am trying the file upload using the ajax way. The configuration I used is given below

    Liferay 6.2
    Eclispe Java EE IDE for Web Developers (Luna Release)
    Tomcat 7.0.42
    jQuery http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js and https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js

    When I run my portlet, I do get the file uploaded. However I do see the following error in the browser console. And I don't see any alert in the ajax callback. Any idea why?

    POST http://localhost:8080/web/guest/spring-event?p_p_id=helloworld_WAR_hellowor…adFile&p_p_cacheability=cacheLevelPage&p_p_col_id=column-1&p_p_col_count=1 net::ERR_CONTENT_DECODING_FAILED jquery.min.js:3
    f.event.trigger jquery.min.js:3
    (anonymous function) jquery.min.js:3
    e.extend.each jquery.min.js:2
    e.fn.e.each jquery.min.js:2
    f.fn.extend.trigger jquery.min.js:3
    f.fn.(anonymous function) jquery.min.js:3
    jQuery.extend.ajaxFileUpload ajaxfileupload.js:169
    uploadFileInAjax spring-event:3
    (anonymous function) spring-event:3
    f.event.dispatch jquery.min.js:3
    h.handle.i jquery.min.js:3

    Uncaught TypeError: undefined is not a function ajaxfileupload.js:87
    uploadCallback ajaxfileupload.js:87

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete