Thursday, May 28, 2015

How to upload a file in your server.

In your view.jsp paste this

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui"%>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
<portlet:defineObjects />

<portlet:actionURL name="upload" var="uploadFileURL"></portlet:actionURL>

<aui:form action="<%= uploadFileURL %>" enctype="multipart/form-data" method="post">

<select name="folder">
  <option value="store">Store</option>
  <option value="floor">Floor</option>
  <option value="department">Department</option>
</select>

<aui:input type="file" name="fileupload" />
<aui:button name="Save" value="Save" type="submit" />

</aui:form>

and in your controller:

package com.test.upload;
import java.io.File;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;

import org.apache.commons.io.FileUtils;

import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

public class UploadDirectory extends MVCPortlet {

    private final static int ONE_GB = 1073741824;
  
    private final static String baseDir = "/home/xxxcompny/Test/Floor";

    private final static String fileInputName = "fileupload";

    public void upload(ActionRequest request, ActionResponse response)
            throws Exception {

        UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);

        long sizeInBytes = uploadRequest.getSize(fileInputName);

        if (uploadRequest.getSize(fileInputName) == 0) {
            throw new Exception("Received file is 0 bytes!");
        }

      
        File uploadedFile = uploadRequest.getFile(fileInputName);

        String sourceFileName = uploadRequest.getFileName(fileInputName);

      
      
        File folder = new File(baseDir);
      
        if (folder.getUsableSpace() < ONE_GB) {
            throw new Exception("Out of disk space!");
        }

      
        File filePath = new File(folder.getAbsolutePath() + File.separator + sourceFileName);

      
        FileUtils.copyFile(uploadedFile, filePath);
    }

}

4 comments:

  1. http://stackoverflow.com/questions/6059453/how-to-provide-relative-path-in-file-class-to-upload-any-file

    ReplyDelete
  2. UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);

    String submissionFileName = uploadRequest.getFileName("file");
    File submissionFile = uploadRequest.getFile("file");
    File destination = null;

    ReplyDelete
  3. Are you doing write somewhere there you have to do like below

    File file = new File("/path/to/uploaded/files", filename);

    item.write(file);

    ReplyDelete
  4. stuck with the thing "item" which is not resolved

    ReplyDelete