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.