Home Liferay Multiple File Upload in Liferay
formats

Multiple File Upload in Liferay

Published on June 29, 2014, by in Liferay.

Hello Open Source Gurus, This blog is all about how to upload multiple files in document and library using Alloy UI. Please find the list of things that you are going to need before implementation of multiple file upload. Prerequisites for Multiple File Upload in Liferay

  • Liferay 6.2 CE ga1
  • Plugin SDK 6.2

Step 1 : Create new liferay project “UploadMultipleFile-portlet”. 1 Step 2 : Create new package com.upload.controller in docroot/WEB-INF/src. 2 3 Step 3 : Create MVC portlet “UploadMultipleFileController” under com.upload.controller package. 5 4 Step 4 : Create new folder html under docroot and move view.jsp file in html folder. 6 7 Step 5 : Define your controller class and view.jsp file in portlet.xml. 8 Step 6 : Create doview() method in UploadMultipleFileController.java file.

public void doView(RenderRequest renderRequest,RenderResponse renderResponsethrows PortletException, IOException {

renderRequest.setAttribute(isAdmin“, PortalUtil.isOmniadmin(PortalUtil.getUserId(renderRequest)));

include(viewTemplaterenderRequestrenderResponse);

}

9

Step 7 : add jstlapi.jar and jstlimpl.jar file in liferay-plugin-package.properties file.

portal-dependency-jars=\

jstlapi.jar,\

jstlimpl.jar

10

Step 8: Create init.jsp file under docroot/html/ and add tag liberary in it.

  <%@ page isELIgnored=“false” %>

<%@ taglib uri=“http://java.sun.com/portlet_2_0” prefix=portlet%>

<%@ taglib uri=“http://java.sun.com/jsp/jstl/core” prefix=“c” %>

<%@ taglib uri=“http://java.sun.com/jsp/jstl/functions” prefix=fn%>

<%@ taglib prefix=fmt uri=“http://java.sun.com/jsp/jstl/fmt” %>

<%@ taglib uri=“http://liferay.com/tld/portlet” prefix=“liferay-portlet”%>

<%@ taglib uri=“http://liferay.com/tld/theme” prefix=liferay-theme”%>

<%@ taglib uri=“http://liferay.com/tld/ui” prefix=“liferay-ui”%>

<%@ taglib uri=“http://liferay.com/tld/util” prefix=“liferay-util”%>

<%@ taglib uri=“http://liferay.com/tld/aui” prefix=aui %>

<portlet:defineObjects />

<liferay-theme:defineObjects/>

Step 9: Add following code in view.jsp file.

<%@ include file=“init.jsp”%>

<c:choose>

<c:when test=${isAdmin}

>

<div class=“alert

alert-info” style=”cursor: pointer;text-align: center; onClick=<%= responseenderR.getNamespace() + “openFileUploadPopup();”%>>

<liferayui:message key=“click-here-to-upload-file” />

</div>

</c:when>

<c:otherwise>

<div class“portl=et-msg-error” style=“text-align: center;”>

<liferayui:message key=“please-sign-in-to-upload-files />

</div>

</c:other

wise>

</c:choose>

Step 10: Create one jsp files upload_multiple_file.jsp under docroot/html folder and create render URL in init.jsp.

<%@page import=com.raylife.portal.kernel.portlet.LiferayWindowState”%>

<liferay-portlet:renderURL var=“uploadMultipleFileURL” windowState=<%= LiferayWindowState.POP_UP.toString() %>>

<portlet:param name=jspPage value=<%=”/html/upload_multiple_file.js

p“%> />

</liferaypor

tlet:renderURL>

Step 11: Create view_js.jsp file in docroot/html/ and following code in it.

<%@includefile=“init.jsp”%>

<aui:script use=aui-base,liferayportlet-url”>

<portlet:namespace />openFileUploadPopup = function() {

boxId = id;

Liferay.Util.selectEntity(

{

dialog: {

constrain: true,

modal: true,

width: 1400

},

id: ‘fileUploadPopup’+id,

title: ‘<liferayui:message key=“upload-multiple-files

/

>’

,

ur

iuploadMultipleFileU:’%<=R L.toString() %>’

}

);

}

</aui:script>

Step 12 : Include view_js.jsp file in view.jsp at bottom of view.jsp.

<%@ include file=“view_js.jsp”%>

Step 13: Add following code for drag and drop liferay aui upload file container in upload_multiple_file.jsp.

<%@includefile=“init.jsp”%>

<%@page import=com.liferay.portlet.documentlibrary.model.DLFileEntryConstants”%>

<%@page import=com.upload.controller.UploadMultipleFileController”%>

<%@page import=com.liferay.portal.kernel.repository.model.Folder”%>

<%@page import=com.sun.mail.imap.DefaultFolder%>

<%@page import=com.liferay.util.portlet.PortletProps”%>

<%@page import=com.liferay.portlet.documentlibrary.service.DLAppServiceUtil”%>

<%@page import=com.liferay.portal.kernel.language.LanguageUtil”%>

<%@page import=com.liferay.portal.util.PortalUtil”%>

<%@page import=com.liferay.portlet.documentlibrary.util.DLUtil”%>

<%@page import=com.liferay.portlet.documentlibrary.model.DLFolderConstants”%>

<%@page import=com.liferay.portal.kernel.util.GetterUtil”%>

<%@page import=com.liferay.portal.service.ServiceContext%>

<%@page import=com.liferay.portal.model.TicketConstants”%>

<%@page import=com.liferay.portal.model.User”%>

<%@page import=com.liferay.portal.model.Ticket”%>

<%@page import=com.liferay.portal.service.TicketLocalServiceUtil”%>

<%@page import=com.liferay.portal.kernel.util.Time”%>

<%@page import=com.liferay.portal.kernel.util.Constants”%>

<%@page import=com.liferay.portal.kernel.util.StringPool”%>

<%@page import=com.liferay.portal.kernel.util.PropsKeys”%>

<%@page import=com.liferay.portal.kernel.util.PrefsPropsUtil”%>

<%@page import=com.liferay.portal.kernel.util.StringUtil”%>

<%@page import=com.liferay.portlet.documentlibrary.model.DLFolderConstants”%>

<%@page import=com.liferay.portal.kernel.language.UnicodeLanguageUtil”%>

<%@page import=java.util.*”%>

<aui:row>

<aui:col width=<%= 50 %>>

<aui:form name=“fm1”>

<div class=lfr-dynamic-uploader>

<div class=lfr-upload-container” id=<portlet:namespace />multipleFileUpload></div>

</div>

</aui:form>

<%

Ticket ticket = TicketLocalServiceUtil.addTicket(user.getCompanyId(), User.class.getName(), user.getUserId(), TicketConstants.TYPE_IMPERSONATE, null, null, new ServiceContext());

%>

<aui:script use=liferay-upload”>

new Liferay.Upload(

{

boundingBox: ‘#<portlet:namespace />multipleFileUpload‘,

deleteFile: ‘<liferay-portlet:actionURL name=“editMultipleFileEntriesURL” doAsUserId=<%= user.getUserId() %>><portlet:param name=<%= Constants.CMD %> value=<%= Constants.DELETE_TEMP %> /><portlet:param name=“folderId” value=<%= String.valueOf(DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) %> /></liferay-portlet:actionURL>&ticketKey=<%= ticket.getKey() %><liferay-ui:input-permissions-params modelName=<%= DLFileEntryConstants.getClassName() %> />‘,

fileDescription: ‘<%= StringUtil.merge(PrefsPropsUtil.getStringArray(PropsKeys.DL_FILE_EXTENSIONS, StringPool.COMMA)) %>‘,

maxFileSize: ‘<%= PrefsPropsUtil.getLong(PropsKeys.DL_FILE_MAX_SIZE) %> ‘,

metadataContainer: ‘#<portlet:namespace />commonFileMetadataContainer‘,

metadataExplanationContainer: ‘#<portlet:namespace />metadataExplanationContainer‘,

namespace: ‘<portlet:namespace />‘,

tempFileURL: {

method: Liferay.Service.bind(‘/dlapp/get-temp-file-entry-names’),

params: {

groupId: <%= scopeGroupId %>,

folderId: <%= DLFolderConstants.DEFAULT_PARENT_FOLDER_ID %>,

tempFolderName: ‘com.upload.controller.UploadMultipleFileController’

}

},

tempRandomSuffix: ‘<%=“–tempRandomSuffix–“%>‘,

uploadFile: ‘<liferay-portlet:actionURL name=“editMultipleFileEntriesURL” doAsUserId=<%= user.getUserId() %>><portlet:param name=<%= Constants.CMD %> value=<%= Constants.ADD_TEMP %> /><portlet:param name=“folderId” value=<%= String.valueOf(DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) %> /></liferay-portlet:actionURL>&ticketKey=<%= ticket.getKey() %><liferay-ui:input-permissions-params modelName=<%= DLFileEntryConstants.getClassName() %> />

}

);

</aui:script>

</aui:col>

<aui:col width=<%= 50 %>>

<div class=“common-file-metadata-container hide selected” id=<portlet:namespace />commonFileMetadataContainer>

<%@ include file=“upload_file_resources.jsp” %>

</div>

<aui:script>

Liferay.provide(

window,

<portlet:namespace />updateMultipleFiles‘,

function() {

var A = AUI();

var Lang = A.Lang;

var commonFileMetadataContainer = A.one(‘#<portlet:namespace />commonFileMetadataContainer’);

var selectedFileNameContainer = A.one(‘#<portlet:namespace />selectedFileNameContainer’);

var inputTpl = ‘<input id=<portlet:namespace />selectedFileName{0}” name=<portlet:namespace />selectedFileName” type=“hidden” value=“{1}” />‘;

var values = A.all(‘input[name=<portlet:namespace />selectUploadedFileCheckbox]:checked’).val();

var buffer = [];

var dataBuffer = [];

var length = values.length;

for (var i = 0; i < length; i++) {

dataBuffer[0] = i;

dataBuffer[1] = values[i];

buffer[i] = Lang.sub(inputTpl, dataBuffer);

}

selectedFileNameContainer.html(buffer.join(”));

commonFileMetadataContainer.plug(A.LoadingMask);

commonFileMetadataContainer.loadingmask.show();

A.io.request(

document.<portlet:namespace />fm2.action,

{

dataType: ‘json‘,

form: {

id: document.<portlet:namespace />fm2

},

after: {

success: function(event, id, obj) {

var jsonArray = this.get(responseData‘);

for (var i = 0; i < jsonArray.length; i++) {

var item = jsonArray[i];

var checkBox = A.one(‘input[data-fileName=”‘ + item.originalFileName + ‘”]’);

var li = checkBox.ancestor();

checkBox.remove(true);

li.removeClass(‘selectable’).removeClass(‘selected’);

var cssClass = null;

var childHTML = null;

if (item.added) {

cssClass = ‘file-saved’;

var originalFileName = item.originalFileName;

var pos = originalFileName.indexOf(‘–tempRandomSuffix–‘);

if (pos != -1) {

originalFileName = originalFileName.substr(0, pos);

}

if (originalFileName === item.fileName) {

childHTML = ‘<span class=“success-message”><%= UnicodeLanguageUtil.get(pageContext, “successfully-saved”) %></span>‘;

}

else {

childHTML = ‘<span class=“success-message”><%= UnicodeLanguageUtil.get(pageContext, “successfully-saved”) %> (‘ + item.fileName + ‘)</span>‘;

}

}

else {

cssClass = ‘upload-error’;

childHTML = ‘<span class=“error-message”>‘ + item.errorMessage + ‘</span>‘;

}

li.addClass(cssClass);

li.append(childHTML);

}

<liferayportlet:resourceURL copyCurrentRenderParameters=<%=false%> var=uploadMultipleFileEntries>

<portlet:param name=repositoryId value=<%= String.valueOf(themeDisplay.getScopeGroupId()) %> />

<portlet:param name=folderId value=<%= String.valueOf(DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) %> />

</liferayportlet:resourceURL>

commonFileMetadataContainer.load(<%= uploadMultipleFileEntries %>‘);

Liferay.fire(filesSaved‘);

},

failure: function(event, id, obj) {

var selectedItems = A.all(‘#<portlet:namespace />multipleFileUpload li.selected’);

selectedItems.removeClass(‘selectable’).removeClass(‘selected’).addClass(‘upload-error’);

selectedItems.append(<span class=“error-message”><%= UnicodeLanguageUtil.get(pageContext, an-unexpected-error-occurred-while-deleting-the-file”) %></span>‘);

selectedItems.all(‘input’).remove(true);

commonFileMetadataContainer.loadingmask.hide();

}

}

}

);

},

[‘aui-base’]

);

</aui:script>

</aui:col>

</aui:row>

Step 14: Add following code in upload_file_resources.jsp for saving documents in liferay document liberary portlet.

 

<%@pageimport=com.liferay.util.portlet.PortletProps”%>

<%@page import=com.liferay.portlet.documentlibrary.service.DLAppServiceUtil”%>

<%@page import=com.liferay.portlet.documentlibrary.model.DLFolderConstants”%>

<%@page import=“com.liferay.portlet.documentlibrary.model.DLFileEntry”%>

<%@page import=com.liferay.portlet.documentlibrary.model.DLFileEntryConstants”%>

<%@page import=com.liferay.portal.kernel.language.UnicodeLanguageUtil”%>

<%@page import=“com.liferay.portlet.dynamicdatamapping.storage.StorageEngineUtil”%>

<%@page import=“com.liferay.portlet.documentlibrary.service.DLFileEntryMetadataLocalServiceUtil”%>

<%@page import=“com.liferay.portlet.documentlibrary.model.DLFileEntryMetadata”%>

<%@page import=“com.liferay.portlet.dynamicdatamapping.storage.Fields”%>

<%@page import=“com.liferay.portlet.dynamicdatamapping.model.DDMStructure”%>

<%@page import=“com.liferay.portal.kernel.util.HtmlUtil”%>

<%@page import=com.liferay.portal.kernel.util.Constants”%>

<%@page import=“com.liferay.portlet.documentlibrary.service.DLFileEntryTypeLocalServiceUtil”%>

<%@page import=“com.liferay.portlet.documentlibrary.model.DLFileVersion”%>

<%@page import=“com.liferay.portal.kernel.util.ParamUtil”%>

<%@page import=com.liferay.portal.util.PortalUtil”%>

<%@pageimport=com.liferay.portlet.documentlibrary.service.DLFileEntryTypeServiceUtil”%>

<%@page import=“com.liferay.portlet.documentlibrary.model.DLFileEntryType”%>

<%@page import=“com.liferay.portal.kernel.repository.model.FileVersion”%>

<%@page import=“com.liferay.portlet.documentlibrary.model.DLFolder”%>

<%@page import=“com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil”%>

<%@page import=com.liferay.portal.kernel.repository.model.Folder”%>

<%@page import=“com.liferay.portal.kernel.repository.model.FileEntry”%>

<%@page import=“com.liferay.portal.kernel.bean.BeanParamUtil”%>

<%@page import=java.util.*”%>

<%@ include file=“init.jsp” %>

<%

Folder folder = null;

Long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;

FileEntry fileEntry2 = null;

long repositoryId = themeDisplay.getScopeGroupId();

if (folderId > 0) {

folder = DLAppLocalServiceUtil.getFolder(folderId);

}

boolean inherited = true;

if ((folder != null) && (folder.getModel() instanceof DLFolder)) {

DLFolder dlFolder = (DLFolder)folder.getModel();

inherited = !dlFolder.isOverrideFileEntryTypes();

}

List<DLFileEntryType> fileEntryTypes = DLFileEntryTypeServiceUtil.getFolderFileEntryTypes(PortalUtil.getSiteAndCompanyGroupIds(themeDisplay), folderId, inherited);

FileVersion fileVersion = null;

long fileVersionId = 0;

long fileEntryTypeId = ParamUtil.getLong(request, “fileEntryTypeId”, -1);

if (fileEntry2 != null) {

fileVersion = fileEntry2.getLatestFileVersion();

fileVersionId = fileVersion.getFileVersionId();

if ((fileEntryTypeId == -1) && (fileVersion.getModel() instanceof DLFileVersion)) {

DLFileVersion dlFileVersion = (DLFileVersion)fileVersion.getModel();

fileEntryTypeId = dlFileVersion.getFileEntryTypeId();

}

}

DLFileEntryTypefileEntryType = null;

if ((fileEntryTypeId == -1) && !fileEntryTypes.isEmpty()) {

fileEntryType = fileEntryTypes.get(0);

fileEntryTypeId = fileEntryType.getFileEntryTypeId();

}

if (fileEntryTypeId > 0) {

fileEntryType = DLFileEntryTypeLocalServiceUtil.getFileEntryType(fileEntryTypeId);

}

long assetClassPK = 0;

%>

<portlet:actionURL var=“editMultipleFileEntriesURL” name=“editMultipleFileEntriesURL”>

</portlet:actionURL>

<aui:form action=<%= editMultipleFileEntriesURL %> method=“post” name=“fm2” onSubmit=<%=“event.preventDefault(); “ + liferayPortletResponse.getNamespace() + “updateMultipleFiles();”%>>

<aui:input name=<%= Constants.CMD %> type=“hidden” value=<%= Constants.ADD_MULTIPLE %> />

<aui:input name=“repositoryId” type=“hidden” value=<%= String.valueOf(repositoryId) %> />

<aui:input name=“folderId” type=“hidden” value=<%= String.valueOf(folderId) %> />

<aui:input name=“boxId” type=“hidden” />

<div class=“no-files-selected-info alert alert-info hide” id=<portlet:namespace />metadataExplanationContainer”>

<liferay-ui:message key=“select-documents-from-the-left-to-add-them-to-the-documents-and-media” />

</div>

<aui:model-context bean=<%= fileVersion %> model=<%= DLFileVersion.class%> />

<liferay-ui:panel-container extended=<%=false%> id=“documentLibraryAssetPanelContainer” persistState=<%=true%>>

<div class=“selected-files-count”>

<liferay-ui:message key=“no-files-selected” />

</div>

<c:if test=<%= (folder == null) || folder.isSupportsMetadata() %>>

<aui:input name=“description” />

<c:if test=<%= !fileEntryTypes.isEmpty() %>>

<liferay-ui:panel collapsible=<%=true%> cssClass=“document-type” persistState=<%=true%> title=“document-type”>

<aui:input name=fileEntryTypeId type=“hidden” value=<%= (fileEntryTypeId > 0) ? fileEntryTypeId : 0 %> />

<aui:input name=defaultLanguageId type=“hidden” value=<%= themeDisplay.getLanguageId() %> />

<div class=“document-type-selector”>

<liferay-ui:icon-menu direction=“down” icon=<%= themeDisplay.getPathThemeImages() + “/common/copy.png”%> id=“groupSelector” message=<%= (fileEntryTypeId > 0) ? HtmlUtil.escape(fileEntryType.getName(locale)) : “basic-document”%> showWhenSingleIcon=<%=true%>>

<%

for(DLFileEntryType curFileEntryType : fileEntryTypes) {

%>

<liferayportlet:resourceURL copyCurrentRenderParameters=<%=false%> var=viewFileEntryTypeURL>

<portlet:param name=“struts_action” value=“/document_library/edit_file_entry” />

<portlet:param name=repositoryId value=<%= String.valueOf(repositoryId) %> />

<portlet:param name=“folderId” value=<%= String.valueOf(folderId) %> />

<portlet:param name=“fileEntryTypeId” value=<%= String.valueOf(curFileEntryType.getFileEntryTypeId()) %> />

</liferay-portlet:resourceURL>

<liferay-ui:icon

cssClass=“upload-multiple-document-types”

id=<%=“fileEntryType_” + String.valueOf(curFileEntryType.getFileEntryTypeId()) %>

image=“copy”

message=<%= HtmlUtil.escape(curFileEntryType.getName(locale)) %>

method=“get”

url=<%= viewFileEntryTypeURL %>

/>

<%

}

%>

</liferay-ui:icon-menu>

</div>

<%

if (fileEntryTypeId > 0) {

try {

List<DDMStructure> ddmStructures = fileEntryType.getDDMStructures();

for (DDMStructure ddmStructure : ddmStructures) {

Fields fields = null;

try {

DLFileEntryMetadata fileEntryMetadata = DLFileEntryMetadataLocalServiceUtil.getFileEntryMetadata(ddmStructure.getStructureId(), fileVersionId);

fields = StorageEngineUtil.getFields(fileEntryMetadata.getDDMStorageId());

}

catch (Exception e) {

}

%>

<div class=“document-type-fields”>

<liferay-ddm:html

classNameId=”<%= PortalUtil.getClassNameId(DDMStructure.class) %>

classPK=”<%= ddmStructure.getPrimaryKey() %>

fields=”<%= fields %>

fieldsNamespace=”<%= String.valueOf(ddmStructure.getPrimaryKey()) %>

requestedLocale=”<%= locale %>

/>

</div>

<%

}

}

catch (Exception e) {

}

}

%>

<aui:script use=“aui-base”>

var groupSelectorMenu = A.one(‘#<portlet:namespace />groupSelector’).ancestor().one(‘.lfr-menu-list’);

if (groupSelectorMenu) {

groupSelectorMenu.delegate(

‘click’,

function(event) {

event.preventDefault();

var documentTypeForm = A.one(‘#<portlet:namespace />fm2′);

documentTypeForm.load(

event.currentTarget.attr(‘href’),

{

where: ‘outer’

},

function() {

var selectedFilesCountContainer = A.one(‘.selected-files-count’);

var totalFiles = A.all(‘input[name=<portlet:namespace />selectUploadedFileCheckbox]’);

var totalFilesCount = totalFiles.size();

var selectedFiles = totalFiles.filter(‘:checked’);

var selectedFilesCount = selectedFiles.size();

var selectedFilesText = selectedFiles.item(0).attr(‘data-title’);

if (selectedFilesCount > 1) {

if (selectedFilesCount == totalFilesCount) {

selectedFilesText = ‘<%= UnicodeLanguageUtil.get(pageContext, “all-files-selected”) %>‘;

}

else {

selectedFilesText = A.Lang.sub(‘<%= UnicodeLanguageUtil.get(pageContext, “x-files-selected”) %>‘, [selectedFilesCount]);

}

}

selectedFilesCountContainer.setContent(selectedFilesText);

selectedFilesCountContainer.attr(‘title’, selectedFilesText);

}

);

},

‘li a’

);

}

</aui:script>

</liferay-ui:panel>

</c:if>

<liferay-ui:custom-attributes-available className=<%= DLFileEntryConstants.getClassName() %>>

<liferay-ui:custom-attribute-list

className=<%= DLFileEntryConstants.getClassName() %>

classPK=<%= fileVersionId %>

editable=<%=true%>

label=<%=true%>

/>

</liferay-ui:custom-attributes-available>

</c:if>

<c:if test=<%= (folder == null) || folder.isSupportsSocial() %>>

<liferay-ui:panel cssClass=“categorization-panel” defaultState=“closed” extended=<%=false%> id=“dlFileEntryCategorizationPanel” persistState=<%=true%> title=“categorization”>

<aui:fieldset>

<aui:input classPK=<%= assetClassPK %> model=<%= DLFileEntry.class%> name=“categories” type=“assetCategories” />

<aui:input classPK=<%= assetClassPK %> model=<%= DLFileEntry.class%> name=“tags” type=“assetTags” />

</aui:fieldset>

</liferay-ui:panel>

</c:if>

</liferay-ui:panel-container>

<aui:field-wrapper cssClass=“upload-multiple-file-permissions” label=“permissions”>

<liferay-ui:input-permissions

modelName=<%= DLFileEntryConstants.getClassName() %>

/>

</aui:field-wrapper>

<span id=<portlet:namespace />selectedFileNameContainer”></span>

<aui:button type=“submit” />

</aui:form>

<aui:script>

<c:if test=<%= (folder == null) || folder.isSupportsSocial() %>>

function <portlet:namespace />getSuggestionsContent() {

return document.<portlet:namespace />fm2.<portlet:namespace />description.value;

}

</c:if>

</aui:script>

Step 15: Create action and other helper method in UploadMultipleFileController.java file.

@ProcessAction (name = “editMultipleFileEntriesURL”)

publicvoid updateMultipleFileEntries(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception{

String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

try {

if (cmd.equals(Constants.ADD_MULTIPLE)) {

addMultipleFileEntries(

actionRequest, actionResponse);

actionRequest.setAttribute(“status”, “success”);

}

elseif (cmd.equals(Constants.ADD_TEMP)) {

addTempFileEntry(actionRequest, actionResponse);

}

elseif (cmd.equals(Constants.DELETE_TEMP)) {

deleteTempFileEntry(actionRequest, actionResponse);

}

actionRequest.setAttribute(“status”, “success”);

}

catch (FileSizeException e) {

actionRequest.setAttribute(“status”, “error”);

actionRequest.setAttribute(“fileSizeException”, “Please enter a file with a valid file size no larger than 102400k.”);

}

}

protectedvoid addTempFileEntry(

ActionRequest actionRequest, ActionResponse actionResponse)

throws Exception {

UploadPortletRequest uploadPortletRequest =

PortalUtil.getUploadPortletRequest(actionRequest);

ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(

WebKeys.THEME_DISPLAY);

long folderId = ParamUtil.getLong(uploadPortletRequest, “folderId”);

String sourceFileName = uploadPortletRequest.getFileName(“file”);

String title = sourceFileName;

sourceFileName = sourceFileName.concat(

TEMP_RANDOM_SUFFIX).concat(StringUtil.randomString());

InputStream inputStream = null;

try {

inputStream = uploadPortletRequest.getFileAsStream(“file”);

String contentType = uploadPortletRequest.getContentType(“file”);

DLAppServiceUtil.addTempFileEntry(

themeDisplay.getScopeGroupId(), folderId, sourceFileName,

_TEMP_FOLDER_NAME, inputStream, contentType);

JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

jsonObject.put(“name”, sourceFileName);

jsonObject.put(“title”, title);

writeJSON(actionRequest, actionResponse, jsonObject);

}

catch (Exception e) {

UploadException uploadException =

(UploadException)actionRequest.getAttribute(

WebKeys.UPLOAD_EXCEPTION);

if ((uploadException != null) &&

uploadException.isExceededSizeLimit()) {

thrownew FileSizeException(uploadException.getCause());

}

else {

throw e;

}

}

finally {

StreamUtil.cleanUp(inputStream);

}

}

protectedvoid deleteTempFileEntry(

ActionRequest actionRequest, ActionResponse actionResponse)

throws Exception {

ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(

WebKeys.THEME_DISPLAY);

long folderId = ParamUtil.getLong(actionRequest, “folderId”);

String fileName = ParamUtil.getString(actionRequest, “fileName”);

JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

try {

DLAppServiceUtil.deleteTempFileEntry(

themeDisplay.getScopeGroupId(), folderId, fileName,

_TEMP_FOLDER_NAME);

jsonObject.put(“deleted”, Boolean.TRUE);

}

catch (Exception e) {

String errorMessage = themeDisplay.translate(

“an-unexpected-error-occurred-while-deleting-the-file”);

jsonObject.put(“deleted”, Boolean.FALSE);

jsonObject.put(“errorMessage”, errorMessage);

}

writeJSON(actionRequest, actionResponse, jsonObject);

}

protectedvoid addMultipleFileEntries(

ActionRequest actionRequest,

ActionResponse actionResponse)

throws Exception {

List<KeyValuePair> validFileNameKVPs = new ArrayList<KeyValuePair>();

List<KeyValuePair> invalidFileNameKVPs = new ArrayList<KeyValuePair>();

String[] selectedFileNames = ParamUtil.getParameterValues(

actionRequest, “selectedFileName”);

for (String selectedFileName : selectedFileNames) {

addMultipleFileEntries(

actionRequest, actionResponse, selectedFileName,

validFileNameKVPs, invalidFileNameKVPs);

}

JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

for (KeyValuePair validFileNameKVP : validFileNameKVPs) {

String fileName = validFileNameKVP.getKey();

String originalFileName = validFileNameKVP.getValue();

JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

jsonObject.put(“added”, Boolean.TRUE);

jsonObject.put(“fileName”, fileName);

jsonObject.put(“originalFileName”, originalFileName);

jsonArray.put(jsonObject);

}

for (KeyValuePair invalidFileNameKVP : invalidFileNameKVPs) {

String fileName = invalidFileNameKVP.getKey();

String errorMessage = invalidFileNameKVP.getValue();

JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

jsonObject.put(“added”, Boolean.FALSE);

jsonObject.put(“errorMessage”, errorMessage);

jsonObject.put(“fileName”, fileName);

jsonObject.put(“originalFileName”, fileName);

jsonArray.put(jsonObject);

}

writeJSON(actionRequest, actionResponse, jsonArray);

}

protectedvoid addMultipleFileEntries(

ActionRequest actionRequest,

ActionResponse actionResponse, String selectedFileName,

List<KeyValuePair> validFileNameKVPs,

List<KeyValuePair> invalidFileNameKVPs)

throws Exception {

String originalSelectedFileName = selectedFileName;

ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(

WebKeys.THEME_DISPLAY);

long repositoryId = ParamUtil.getLong(actionRequest, “repositoryId”);

long folderId = ParamUtil.getLong(actionRequest, “folderId”);

String description = ParamUtil.getString(actionRequest, “description”);

String changeLog = ParamUtil.getString(actionRequest, “changeLog”);

FileEntry tempFileEntry = null;

try {

tempFileEntry = TempFileUtil.getTempFile(

themeDisplay.getScopeGroupId(), themeDisplay.getUserId(),

selectedFileName, _TEMP_FOLDER_NAME);

String mimeType = tempFileEntry.getMimeType();

InputStream inputStream = tempFileEntry.getContentStream();

long size = tempFileEntry.getSize();

ServiceContext serviceContext = ServiceContextFactory.getInstance(

DLFileEntry.class.getName(), actionRequest);

int pos = selectedFileName.indexOf(TEMP_RANDOM_SUFFIX);

if (pos != -1) {

selectedFileName = selectedFileName.substring(0, pos);

}

while (true) {

try {

DLAppLocalServiceUtil.getFileEntry(

themeDisplay.getScopeGroupId(), folderId,

selectedFileName);

StringBundler sb = new StringBundler(5);

sb.append(FileUtil.stripExtension(selectedFileName));

sb.append(StringPool.DASH);

sb.append(StringUtil.randomString());

sb.append(StringPool.PERIOD);

sb.append(FileUtil.getExtension(selectedFileName));

selectedFileName = sb.toString();

}

catch (Exception e) {

break;

}

}

FileEntry fileEntry = DLAppServiceUtil.addFileEntry(

repositoryId, folderId, selectedFileName, mimeType,

selectedFileName, description, changeLog, inputStream, size,

serviceContext);

AssetPublisherUtil.addAndStoreSelection(

actionRequest, DLFileEntry.class.getName(),

fileEntry.getFileEntryId(), -1);

AssetPublisherUtil.addRecentFolderId(

actionRequest, DLFileEntry.class.getName(), folderId);

validFileNameKVPs.add(

new KeyValuePair(selectedFileName, originalSelectedFileName));

return;

}

catch (Exception e) {

String errorMessage = getAddMultipleFileEntriesErrorMessage(

actionRequest, actionResponse, e);

invalidFileNameKVPs.add(

new KeyValuePair(originalSelectedFileName, errorMessage));

}

finally {

if (tempFileEntry != null) {

TempFileUtil.deleteTempFile(tempFileEntry.getFileEntryId());

}

}

}

protected String getAddMultipleFileEntriesErrorMessage(

ActionRequest actionRequest,

ActionResponse actionResponse, Exception e)

throws Exception {

String errorMessage = null;

ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(

WebKeys.THEME_DISPLAY);

if (e instanceof AssetCategoryException) {

AssetCategoryException ace = (AssetCategoryException)e;

AssetVocabulary assetVocabulary = ace.getVocabulary();

String vocabularyTitle = StringPool.BLANK;

if (assetVocabulary != null) {

vocabularyTitle = assetVocabulary.getTitle(

themeDisplay.getLocale());

}

if (ace.getType() == AssetCategoryException.AT_LEAST_ONE_CATEGORY) {

errorMessage = themeDisplay.translate(

“please-select-at-least-one-category-for-x”,

vocabularyTitle);

}

elseif (ace.getType() ==

AssetCategoryException.TOO_MANY_CATEGORIES) {

errorMessage = themeDisplay.translate(

“you-cannot-select-more-than-one-category-for-x”,

vocabularyTitle);

}

}

elseif (e instanceof DuplicateFileException) {

errorMessage = themeDisplay.translate(

“the-folder-you-selected-already-has-an-entry-with-this-name.” +

“-please-select-a-different-folder”);

}

elseif (e instanceof FileExtensionException) {

errorMessage = themeDisplay.translate(

“please-enter-a-file-with-a-valid-extension-x”,

StringUtil.merge(

getAllowedFileExtensions(

actionRequest, actionResponse)));

}

elseif (e instanceof FileNameException) {

errorMessage = themeDisplay.translate(

“please-enter-a-file-with-a-valid-file-name”);

}

elseif (e instanceof FileSizeException) {

long maxSizeMB = com.liferay.portal.kernel.util.PrefsPropsUtil.getLong(

PropsKeys.DL_FILE_MAX_SIZE) / 1024 / 1024;

errorMessage = themeDisplay.translate(

“file-size-is-larger-than-x-megabytes”, maxSizeMB);

}

elseif (e instanceof InvalidFileEntryTypeException) {

errorMessage = themeDisplay.translate(

“the-document-type-you-selected-is-not-valid-for-this-folder”);

}

else {

errorMessage = themeDisplay.translate(

“an-unexpected-error-occurred-while-saving-your-document”);

}

return errorMessage;

}

protected String[] getAllowedFileExtensions(

PortletRequest portletRequest,

PortletResponse portletResponse)

throws PortalException, SystemException {

String portletName = “SampleMockup”;

if (!portletName.equals(PortletKeys.MEDIA_GALLERY_DISPLAY)) {

return com.liferay.portal.kernel.util.PrefsPropsUtil.getStringArray(

PropsKeys.DL_FILE_EXTENSIONS, StringPool.COMMA);

}

else {

PortletPreferences portletPreferences = PortletPreferencesFactoryUtil.getPortletPreferences((HttpServletRequest) portletRequest, “UploadMultipleFile”);

if (portletPreferences == null) {

portletPreferences = portletRequest.getPreferences();

}

Set<String> extensions = new HashSet<String>();

String[] mimeTypes = DLUtil.getMediaGalleryMimeTypes(

portletPreferences, portletRequest);

for (String mimeType : mimeTypes) {

extensions.addAll(MimeTypesUtil.getExtensions(mimeType));

}

return extensions.toArray(new String[extensions.size()]);

}

}

privatestatic Log log = LogFactoryUtil.getLog(UploadMultipleFileController.class);

privatestaticfinal String _TEMP_FOLDER_NAME =

UploadMultipleFileController.class.getName();

publicstaticfinal String TEMP_RANDOM_SUFFIX = “–tempRandomSuffix–“;

Step 16: Deploy your portlet and upload multiple files.

13 14 15 16 17

Step 17: Check your document and media portlet.you can see multiple files that you have uploaded.

Share!Share on FacebookShare on Google+Share on LinkedInTweet about this on TwitterFlattr the authorDigg thisPin on PinterestEmail this to someoneShare on StumbleUponShare on RedditShare on TumblrBuffer this pagePrint this page
Tags:
Comments Off on Multiple File Upload in Liferay.
Copyright © 2017 - Scalsys. All Rights Reserved