Upload file in Liferay
can any one help me How can i upload my file in document and media folder using DLFileEntry
I search but didn't get exact code. How can i do this.
I just put my file controller in jsp file.
I tries using following code
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
String sourceFileName = uploadRequest.getFileName("fileName");
System.out.println("file name " + sourceFileName);
File file = uploadRequest.getFile("fileName");
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
System.out.println("User Id " + themeDisplay.getUserId() + ": " + themeDisplay.getScopeGroupId());
long FOLDER_ID = 0;
long repositoryId = themeDisplay.getScopeGroupId();
long parentFolderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
List<Folder> lFolder = DLAppServiceUtil.getFolders(repositoryId, parentFolderId);
for (Folder folder : lFolder) {
System.out.println(lFolder);
System.out.println(folder.getFolderId());
}
//ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
ServiceContext serviceContext = ServiceContextFactory.getInstance(FileEntry.class.getName(), actionRequest);
System.out.println("hello");
long defaultRepoId = DLFolderConstants.getDataRepositoryId(themeDisplay.getScopeGroupId(),DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
DLFileEntry dlFileEntry=DLFileEntryLocalServiceUtil.addFileEntry(themeDisplay.getUserId(),themeDisplay.getScopeGroupId(), defaultRepoId, 12518, sourceFileName, MimeTypesUtil.getContentType(file), "fileTitle", "fileDesc", "sss",0,null,file,null,file.length(),serviceContext);
DLFileEntryLocalServiceUtil.updateFileEntry(themeDisplay.getUserId(), dlFileEntry.getFileEntryId(), sourceFileName, MimeTypesUtil.getContentType(file), "fileTitle", "fileDesc", "comment", true, dlFileEntry.getFileEntryTypeId(), null,file, null, file.length(), serviceContext);
But didn't get success.
Can any one copy paste code here please?
Thanks in advance
In case anyone stumbles across this:
upload_file.jsp:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<portlet:defineObjects />
<portlet:actionURL name='uploadFile' var="uploadFileURL" windowState="normal" />
<aui:form action="<%= uploadFileURL %>" method="POST" name="fm" enctype="multipart/form-data">
<aui:fieldset>
<aui:input type="file" name="file-to-upload"/>
<aui:button-row>
<aui:button type="submit" />
</aui:button-row>
</aui:fieldset>
</aui:form>
MyPortlet.java:
public class MyPortlet extends MVCPortlet {
//action method
public void uploadFile(ActionRequest request, ActionResponse response)
throws Exception {
UploadPortletRequest uploadRequest
= PortalUtil.getUploadPortletRequest(request);
ServiceContext serviceContext = ServiceContextFactory.getInstance(
MyPortlet.class.getName(), uploadRequest);
this.uploadFileEntity(serviceContext, uploadRequest);
response.setRenderParameter("mvcPath", "/html/view.jsp");
}
// Create a folder called "A_FOLDER" in Documents & Media
private void uploadFileEntity(ServiceContext serviceContext,
UploadPortletRequest request)
throws PortalException, SystemException {
String filename = "";
String description = "File description";
try{
// serviceContext.scopeGroupId is the groupId of a site
long repositoryId = DLFolderConstants.getDataRepositoryId(
serviceContext.getScopeGroupId(),
DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
Folder f = DLAppLocalServiceUtil.getFolder(
repositoryId, 0L, "A_FOLDER");
long folderId = f.getFolderId();
File file = request.getFile("file-to-upload");
filename = request.getFileName("file-to-upload");
String mimeType = MimeTypesUtil.getContentType(file);
FileEntry entry = DLAppLocalServiceUtil.addFileEntry(serviceContext.getUserId(),
repositoryId, folderId, filename,
mimeType, filename, description, "",
file, serviceContext
);
}catch(PortalException e){
_log.error("An exception occured uploading file: "
+ e.getMessage());
throw e;
}catch(SystemException e ){
_log.error("An exception occured uploading file: "
+ e.getMessage());
throw e;
}
}
private static Log _log = LogFactoryUtil.getLog(MyPortlet.class);
}
Related
Is it possible to somehow handle error on loading a PDF?
<p:media value="/resources/media/myDoc.pdf" width="100%" height="800px" zoom="100" player="pdf" cache="false"<>/p:media>
Let's say the PDF document it's not there and won't find it, If that happens my web app crash. Possible to handle it? So I show an error message instead in growl for example?
Thanks
You can check the #Jasper de Vries comment, otherwise you can verify if the file is present using a bean method like this:
MyBean.java
public String findFileURL() {
String fileName = "myDoc.pdf";
String relativeWebPath = "/resources/media/" + fileName;
FacesContext facesContext = FacesContext.getCurrentInstance();
String absoluteDiskPath = ((ServletContext) facesContext.getExternalContext().getContext())
.getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
if (file.isFile()) {
return relativeWebPath;
} else {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "File: " + fileName + " not found.", "");
facesContext.addMessage(null, message);
return "";
}
}
MyPage.xhtml
<p:media value="#{myBean.findFileURL()}" width="100%" height="800px" zoom="100" player="pdf" cache="false"/>
After I upload a file, I would want to be able to delete it. I tried doing so, but I get the error "The resource cannot be found". Also, how can I make edit buttons for every file from the row, in order to upload a better version of that specific file? Could someone help me?
This is my controller:
public class FileUploadController : Controller
{
// GET: FileUpload
public ActionResult Index()
{
var items = GetFiles();
return View(items);
}
// POST: FileUpload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if(file != null && file.ContentLength > 0 )
try
{
string path = Path.Combine(Server.MapPath("~/Files"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch(Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
var items = GetFiles();
return View(items);
}
public FileResult Download(string downloadedfile)
{
var FileVirtualPath = "~/Files/" + downloadedfile;
return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
}
private List <string> GetFiles()
{
var dir = new System.IO.DirectoryInfo(Server.MapPath("~/Files"));
System.IO.FileInfo[] fileNames = dir.GetFiles("*.*");
List<string> items = new List<string>();
foreach (var file in fileNames)
{
items.Add(file.Name);
}
return items;
}
[HttpPost]
public ActionResult Delete(string file)
{
file = Path.Combine(Server.MapPath("~/Files"), file);
FileInfo fl = new FileInfo(file);
if (fl != null)
{
System.IO.File.Delete(file);
fl.Delete();
}
return View();
}
}
}
This is the view, the only problem with it is the Delete section:
<h2> File Upload </h2>
#model List<string>
#using (Html.BeginForm("Index", "FileUpload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file"> Upload </label>
<input type="file" name="file" id="file" />
<br /><br />
<input type="submit" value="Upload" />
<br /><br />
#ViewBag.Message
<br />
<h2>Documents list</h2>
<table style="width:100%">
<tr>
<th> File Name </th>
<th> Link </th>
</tr>
#for (var i = 0; i <= (Model.Count) - 1; i++)
{
<tr>
<td>#Model[i].ToString() </td>
<td>#Html.ActionLink("Download", "Download", new { downloadedfile = Model[i].ToString() }) </td>
<td>#Html.ActionLink("Delete", "Delete", new { deletedfile = Model[i].ToString() }) </td>
</tr>
}
</table>
}
In the form you're posting to the delete method, there is nothing indicating what the path to the file to delete is. You do have a hidden input for the Count property, but if that was a hidden input named "file" and contained the path value for the file to be deleted, then it would be posted.
Note, for security reasons you likely do NOT want to allow people to just post the path to any file and the server will delete it. That could get you into a lot of trouble. You likely should be storing a database record with the file url and an ID and posting that ID to the server, and reading the URL from the database, then deleting the file.
and I cant' store file more than 10Mb
the primary problrm is why doesn't except pdf file???
this is my ManagedBean
file upload function :-
public void fileUploadListener(FileUploadEvent e) throws IOException, Exception {
this.file = e.getFile();
File oStream = new File("c:\\test.pdf");
courseResourceBean.update(item);
oStream.createNewFile();
Long sss = file.getSize();
InputStream inputStream = file.getInputstream();
FileOutputStream outputStream = new FileOutputStream(oStream);
byte[] buffer = new byte[sss.byteValue()];
int lenght;
while ((lenght = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, lenght);
}
outputStream.close();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("File Uploaded Successfully" + file.getSize()));
String extension = file.getContentType();
}
file download function :-
public void prepDownload(Long id) throws Exception {
File files = new File("c:\\test.pdf");
InputStream input = new FileInputStream(files);
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
setDownload(new DefaultStreamedContent(input, externalContext.getMimeType(files.getName()), files.getName()));
System.out.println("PREP = " + download.getName());
}
and this is the xhtml page
upload :-
<p:outputLabel value="#{msg.courseName}, #{msg.inArabic}" style="text-align: right"/>
<p:fileUpload value="#{courseResourceMB.file}" mode="advanced" sizeLimit="200000000000"
fileUploadListener="#{courseResourceMB.fileUploadListener}" update="msg11" >
</p:fileUpload>
downlad:-
<p:commandButton id="downloadLink" value="Download" actionListener="#{courseResourceMB.prepDownload(item.id)}" ajax="false">
<p:fileDownload value="#{courseResourceMB.download}" />
</p:commandButton>
I am building a test application with java6, JSF2.0 on WebSphere Portal 8.0.0.3 to achieve the file upload functionality.
FileUploadView.xhtml
<h:form enctype="multipart/form-data">
<input type="file" name="fileItem1" />
<h:commandButton value="submit" action="#{bean.submit}" />
</h:form>
FileUploadPortlet.java
class FileUploadPortlet extends com.ibm.faces20.portlet.FaceletPortlet{
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException {
boolean isMultipart = PortletFileUpload.isMultipartContent(request);
try {
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
PortletFileUpload upload = new PortletFileUpload(factory);
List /* FileItem */ items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
} else {
String fileName = item.getName();
long sizeInBytes = item.getSize();
System.out.println("FileName is: "+fileName+" Size is: "+sizeInBytes);
}
}
}
} catch ( Exception e) {
System.out.println("SampleFileUploadPortlet.processAction() Error occured");
e.printStackTrace();
}
}
}
portlet.xml
<portlet>
<portlet-name>FileUploadView</portlet-name>
<portlet-class>com.code.FileUploadPortlet</portlet.class>
........
</portlet>
FileIploadManagedBean.java
#ManagedBean(name = "bean")
#SessionScoped
public class FileIploadManagedBean{
public void submit(){
System.out.println("Hello i am in managed bean!!");
}
}
When I am trying to submit the form, I can get the file in processAction method of FileUploadPortlet.java. But my submit method of managed bean is not getting called.
But when I remove enctype="multipart/form-data" from my form. Submit method of managed bean is getting called before processAction method of FileUploadPortlet and file is not visible in this processAction method.
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ValidatorException;
import com.liferay.util.bridges.mvc.MVCPortlet;
public class GreetingMessage extends MVCPortlet {
public static final String GREETING = "greeting";
public static final String DEFAULT_GREETING = "Hello! It's my default greeting message";
#Override
public void render(RenderRequest request, RenderResponse response)
throws IOException, PortletException {
PortletPreferences preferences = request.getPreferences();
request.setAttribute(GREETING,
preferences.getValue(GREETING, DEFAULT_GREETING));
super.render(request, response);
}
public void updateGreeting(ActionRequest request, ActionResponse response)
throws ValidatorException, IOException, ReadOnlyException {
String greeting = request.getParameter("greeting");
PortletPreferences prefs = request.getPreferences();
if (greeting != null) {
prefs.setValue(GREETING, greeting);
prefs.store();
request.setAttribute(GREETING, greeting);
}
}
}
view.jsp:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<p>${greeting}</p>
<portlet:renderURL var="editGreetingURL">
<portlet:param name="mvcPath" value="/html/greetingmessage/edit.jsp"/>
</portlet:renderURL>
<p>Edit greeting</p>
edit.jsp
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%# page import="javax.portlet.PortletPreferences" %>
<portlet:defineObjects />
<portlet:actionURL name="updateGreeting" var="updateGreetingURL">
</portlet:actionURL>
<aui:form action="<%= updateGreetingURL %>" method="post">
<aui:input label="greeting" name="greeting" type="text" value="${greeting}" />
<aui:button type="submit" />
</aui:form>
<portlet:renderURL var="viewGreetingURL">
<portlet:param name="mvcPath" value="/html/greetingmessage/view.jsp" />
</portlet:renderURL>
<p>← AND NOW IT'S BACK</p>
It's tested code of my "edit-greeting" portlet. The question is, how can I make localization??? I've read a lot of docs but it's all for nothing. I created in WEB-INF folder src/language.properties and src/language_es.properties. What should I do next? Help me please. #Shivam
To Answer your question
1)You can handle your attributes and portlet preferences in render method and set them as attributes in render request,which can be subsequently read in your jsp via some scripting language like jstl
2)There is no need to make changes in portlet.xml file.
The init params as the name suggests are added to provide some params needed for initializing a portlet view.
You need to make the below changes to the render method
public void render(RenderRequest req,RenderResponse res) throws IOException, PortletException
{
String greeting = req.getParameter("greeting");
PortletPreferences prefs = req.getPreferences();
String defaultGreeting="Hello! Welcome to our portalOLOLOLOLOL.";
if(prefs.getValue("greeting","true")==null)
{
prefs.setValue("greeting", defaultGreeting);
}
if (greeting != null)
{
prefs.setValue("greeting", greeting);
prefs.store();
req.setAttribute("greeting", prefs.getValue("greeting","true"));
}
else
{
req.setAttribute("greeting", prefs.getValue("greeting","true"));
}
super.render(req,res);
}
There will not be any changes required in view.jsp and edit.jsp(apart from removing code),Hence I forgot to mention the same.
As for the render method,the best approach would be defintely to use action url and use action method,but since it seems you are looking to try out some approach and to make mininmum changes to your,I have kept it render only.
As for the code,the prefs.getValue("greeting","true") checks whether a certain attribute is present in portlet preferences or not.
Updated with process action
public class NewPortlet extends MVCPortlet {
public static final String GREETING="greeting";
#Override
public void render(RenderRequest req,RenderResponse res) throws IOException, PortletException
{
PortletPreferences prefs = req.getPreferences();
String defaultGreeting="Hello! Welcome to our portalOLOLOLOLOL.";
if(prefs.getValue(GREETING,"true")==null)
{
prefs.setValue(GREETING, defaultGreeting);
prefs.store();
}
req.setAttribute(GREETING, prefs.getValue(GREETING,"true"));
super.render(req,res);
}
public void updateGreeting(ActionRequest req,ActionResponse res) throws ValidatorException, IOException, ReadOnlyException
{
String greeting = req.getParameter("greeting");
PortletPreferences prefs = req.getPreferences();
if (greeting != null)
{
prefs.setValue(GREETING, greeting);
prefs.store();
req.setAttribute(GREETING, greeting);
}
}
}
Updates in edit jsp
<portlet:actionURL name="updateGreeting" var="updateGreetingURL">
</portlet:actionURL>
<aui:form action="<%= updateGreetingURL %>" method="post">
<aui:input label="greeting" name="greeting" type="text" value="${greeting}" />
<aui:button type="submit" />
</aui:form>