Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Download multiple files from media and document in Liferay 6.2

    • 0
    • 4
    • 1
    • 4
    • 1
    • 0
    • 0
    • 0
    • 3.27k
    Comment on it

    Hello Guys,

    Liferay store files using media and document which is default functionality of liferay. Liferay support all type file.

    Below code download files with zip folder using "FileEntryID".

    NOTE : Liferay fully support to Oracle JDK.

    Follow below steps to download files from media and document in liferay.

    Step 1 : Create serveResource URL with fileEntryId parameter's.

    Step 2 : Put below code in MVCPortlet class.

          private static final String FILE_EXT_SEP = FilenameUtils.EXTENSION_SEPARATOR_STR;
        private static final String ZIP_FILE_EXT_NAME = "zip";
        private static final String ZIP_FILE_EXT = FILE_EXT_SEP + ZIP_FILE_EXT_NAME;
        private static int DEFAULT_DL_FILE_DOWNLOAD_CACHE_MAX_AGE = 1;
    
    @ProcessAction(name="serveResource")
        public void serveResource(ResourceRequest resourceRequest,
                ResourceResponse resourceResponse) throws IOException 
        {
    
            UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(resourceRequest);
            String files=(String)uploadRequest.getParameter("iFileEntryId");
    
            String [] fileIdsArray = getFileIds(files);
            logger.info("fileDownload   "+fileIdsArray[0]);
            if (null == fileIdsArray || files.isEmpty()) {
                SessionErrors.add(resourceRequest, "Please Select File.");
                resourceResponse.setProperty("portlet.http-status-code", "302");
                resourceResponse.addProperty("Location", resourceResponse.createRenderURL().toString());
                return;
            }
    
            setupResponseHeaders(resourceRequest, resourceResponse);
    
            try {
    
                downloadMultipleFilesInZip(resourceRequest, resourceResponse, fileIdsArray);
            } catch (PortalException e) {
                logger.debug("PortalException", e);
            }
    
        }
    
        private String[] getFileIds(String fileEntryIds) {
            String[] ids = fileEntryIds.split(",");
            return ids;
        }
    private void setupResponseHeaders(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
    
            String zipFileMimeType = "application/zip";
            resourceResponse.setContentType(zipFileMimeType);
            int multipleFileDownloadCacheMaxAge = DEFAULT_DL_FILE_DOWNLOAD_CACHE_MAX_AGE;
            if (multipleFileDownloadCacheMaxAge > 0) {
                String cacheControlValue = "max-age=" + multipleFileDownloadCacheMaxAge + ", must-revalidate";
                resourceResponse.addProperty("Cache-Control", cacheControlValue);
            }
    
            String zipFileName = "ATTACHMENTS_" + new Date().getTime() + ZIP_FILE_EXT;
            String contentDispositionValue = "attachment; filename=\"" + zipFileName + "\"";
            logger.info("resourceResponse>>>> "+contentDispositionValue);
            resourceResponse.addProperty("Content-Disposition", contentDispositionValue);
    
        }
    private void downloadMultipleFilesInZip(ResourceRequest resourceRequest, ResourceResponse resourceResponse, String[] fileIdsArray) throws PortalException {
        try {
            DownloadFilesZipHelper.exportMultipleFilesToZipFile( fileIdsArray, resourceResponse.getPortletOutputStream());
            logger.info("resourceResponse.getPortletOutputStream() >>>> "+resourceResponse.getPortletOutputStream().toString());
        } catch (Exception e) {
            String msg = "Error downloading files " + e.getMessage();
            logger.error(msg, e);
            throw new PortalException(msg, e);
        } 
    

    Step 3 : Create DownloadFilesZipHelper.java and put below code.

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    import org.apache.commons.io.FilenameUtils;
    
    import com.liferay.portal.kernel.exception.PortalException;
    import com.liferay.portal.kernel.exception.SystemException;
    import com.liferay.portal.kernel.json.JSONArray;
    import com.liferay.portal.kernel.json.JSONFactoryUtil;
    import com.liferay.portal.kernel.json.JSONObject;
    import com.liferay.portal.kernel.log.Log;
    import com.liferay.portal.kernel.log.LogFactoryUtil;
    import com.liferay.portal.kernel.repository.model.FileEntry;
    import com.liferay.portal.kernel.util.StreamUtil;
    import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil;
    import com.model.PatientEvents;
    import com.service.PatientEventsLocalServiceUtil;
    
    public class DownloadFilesZipHelper {
    
        private static final Log log = LogFactoryUtil.getLog(DownloadFilesZipHelper.class);
    
        public static void exportMultipleFilesToZipFile(String[] fileIdsArray, OutputStream outputStream) throws PortalException, SystemException, IOException{
    
            List<FileEntry> filesList = getMultipleFiles(fileIdsArray);
            if (!filesList.isEmpty()) {
                exportMultipleFilesToOutputStream(filesList, outputStream);
            }
        }
    
        public static List<FileEntry> getMultipleFiles(String[] fileIdsArray) throws PortalException, SystemException {
    
            long fileEntryId;
            List<FileEntry> fileEntryList = new ArrayList<FileEntry>();
    
            for (String fileEntry : fileIdsArray) {
                fileEntryId = Long.parseLong(fileEntry);
                fileEntryList.add(DLAppServiceUtil.getFileEntry(fileEntryId));
            }
    
            return fileEntryList;
        }
    
        public static void exportMultipleFilesToOutputStream( List<FileEntry> filesList, OutputStream outputStream) throws IOException, PortalException, SystemException {
    
            ZipOutputStream zipWriter = null;
            try{
                zipWriter = new ZipOutputStream(outputStream);
                exportMultipleFilesToZipWriter( filesList, zipWriter);
            }catch (Exception e) {
                log.debug("Exception", e);
            }finally{
                if (zipWriter != null) {
                    zipWriter.close();
                }
            }
        }
    
        public static void exportMultipleFilesToZipWriter( List<FileEntry> filesList, ZipOutputStream zipOutputStream){
    
            InputStream fileInputStream = null;
            try {
                for (FileEntry fileEntry : filesList) {
    
                    String zipEntryPath = buildZipEntryPath( fileEntry, "", zipOutputStream);
    
                    fileInputStream = fileEntry.getContentStream();             
    
                    zipOutputStream.putNextEntry(new ZipEntry(zipEntryPath));
                    StreamUtil.transfer(fileInputStream, zipOutputStream, false);
    
                }
            } catch (Exception e) {         
                log.debug(e);           
            } finally {
                try {
                    if (fileInputStream != null) {
                        fileInputStream.close();
                        fileInputStream = null;
                    }
                } catch (IOException e) {
                    log.debug("IOException", e);
                }           
            }
        }
    
        private static String buildZipEntryPath( FileEntry fileEntry,
                String folderPath, ZipOutputStream zipOutputStream) throws SystemException,
                PortalException {
            String fileEntryBaseName = fileEntry.getTitle();
            fileEntryBaseName = FilenameUtils.getBaseName(fileEntryBaseName);
            fileEntryBaseName = fileEntryBaseName.replaceAll("\\W+", "_");
            String zipEntryName = folderPath + fileEntryBaseName + FilenameUtils.EXTENSION_SEPARATOR_STR + fileEntry.getExtension();
            log.info("zipEntryName    "+zipEntryName);
            return zipEntryName;
        }
    }
    

 1 Comment(s)

  • Dear bhagwan khichar !

    My working on my project and use you code, but when I click a button to download all file to a zip file, the broswer don't open a pop-up to me.

    please help me in this error.

    here is the picture of server log
    https://drive.google.com/file/d/1rR6lE4AL-be9eYo5NkFhO_HfjrB5Qgi7/view?usp=sharing

    Thank you very much
Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: