Foros de discusión
Using file upload in Liferay with Struts Portlet
Akira Akira, modificado hace 12 años.
Using file upload in Liferay with Struts Portlet
Junior Member Mensajes: 80 Fecha de incorporación: 24/09/10 Mensajes recientes
File jsp
file .java
When I run out:
request: com.liferay.portal.upload.UploadPortletRequestImpl@53678
items: [] ??????
Can who help me ?
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<form name="<portlet:namespace />fm" method="post" enctype="multipart/form-data" action="<portlet:actionURL windowState=" <%="WindowState.NORMAL.toString()" %>"><portlet:param name="struts_action" value="/ext/upload/uploadimage" />">
<table border="2">
<tbody><tr>
<td align="center"><b> upload file </b></td>
</tr>
<tr>
<td>
Choise 1: <input name="file" type="file" id="file">
</td>
<td><input type="submit" name="Submit" value="Submit"></td>
</tr>
</tbody></table>
</form>
file .java
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.portlet.PortletFileUpload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.liferay.portal.struts.PortletAction;
public class ActionUpload extends PortletAction {
public void processAction(ActionMapping mapping, ActionForm form,
PortletConfig config, ActionRequest req, ActionResponse res)
throws Exception {
System.out.println("Process upload");
boolean isMultipart =PortletFileUpload.isMultipartContent(req);
System.out.println("request: "+req);
if (!isMultipart) {
System.out.println("File Not Uploaded");
}else {
FileItemFactory factory = new DiskFileItemFactory();
PortletFileUpload upload = new PortletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(req);
[color=#e43a3a] System.out.println("items: "+items);[/color]
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()){
String name = item.getFieldName();
System.out.println("name: "+name);
String value = item.getString();
System.out.println("value: "+value);
} else {
try {
String itemName = item.getName();
Random generator = new Random();
int r = Math.abs(generator.nextInt());
String reg = "[.*]";
String replacingtext = "";
System.out.println("Text before replacing is:-" + itemName);
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(itemName);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, replacingtext);
}
int IndexOf = itemName.indexOf(".");
String domainName = itemName.substring(IndexOf);
System.out.println("domainName: "+domainName);
String finalimage = buffer.toString()+"_"+r+domainName;
System.out.println("Final Image==="+finalimage);
File savedFile = new File(config.getPortletContext().getRealPath("/")+"uploadedFiles/"+itemName);
item.write(savedFile);
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
}
public ActionForward render(ActionMapping mapping, ActionForm form,
PortletConfig portletConfig, RenderRequest renderRequest,
RenderResponse renderResponse) throws Exception{
return mapping.findForward("ext.upload.view");
}
}
When I run out:
request: com.liferay.portal.upload.UploadPortletRequestImpl@53678
items: [] ??????
Can who help me ?
Anil Sunkari, modificado hace 12 años.
RE: Using file upload in Liferay with Struts Portlet
Expert Mensajes: 427 Fecha de incorporación: 12/08/09 Mensajes recientes
Hi Akira,
Try to get the request like this
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest != null) {
String xxxFileName = uploadRequest.getFileName("file");
File xxFile = uploadRequest.getFile("file");
}
Hope it helps!
Regards,
Anil Sunkari
Try to get the request like this
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest != null) {
String xxxFileName = uploadRequest.getFileName("file");
File xxFile = uploadRequest.getFile("file");
}
Hope it helps!
Regards,
Anil Sunkari
Akira Akira, modificado hace 12 años.
RE: Using file upload in Liferay with Struts Portlet
Junior Member Mensajes: 80 Fecha de incorporación: 24/09/10 Mensajes recientes
Thanks Anil Sunkari for answer .
How I save "file" to path config.getPortletContext().getRealPath("/")+"uploadedFiles/"
I run :
out:
xxxFileName
xxxFileE:\trunk\tomcat\temp\upload_00000000
xxxFileName
xxxFileE:\trunk\tomcat\temp\upload_00000002
name image change ???
String xxxFileName no data.
How I save "file" to path config.getPortletContext().getRealPath("/")+"uploadedFiles/"
I run :
public class ActionUpload extends PortletAction {
public void processAction(ActionMapping mapping, ActionForm form,
PortletConfig config, ActionRequest req, ActionResponse res)
throws Exception {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(req);
if (uploadRequest != null) {
String xxxFileName = uploadRequest.getFileName("file");
File xxFile = uploadRequest.getFile("file");
System.out.println("xxxFileName" + xxxFileName );
System.out.println("xxxFile" + xxFile);
}
}
out:
xxxFileName
xxxFileE:\trunk\tomcat\temp\upload_00000000
xxxFileName
xxxFileE:\trunk\tomcat\temp\upload_00000002
name image change ???
String xxxFileName no data.
Akira Akira, modificado hace 12 años.
RE: Using file upload in Liferay with Struts Portlet
Junior Member Mensajes: 80 Fecha de incorporación: 24/09/10 Mensajes recientes
I want upload a image to server liferay.
Can who help me ?
Can who help me ?
Mani kandan, modificado hace 12 años.
RE: Using file upload in Liferay with Struts Portlet
Expert Mensajes: 492 Fecha de incorporación: 15/09/10 Mensajes recientes
For storing a file you should include,
After uploading the file you can find you file inside tomcat/webapps/ROOT/html/portlet
To get the source code link
String realPath = getPortletContext().getRealPath("/");
String sourceFileName =uploadRequest.getFileName("fileName");
File file = uploadRequest.getFile("fileName");
File newFile=null;
newFile = new File(realPath+"html/portlet"+sourceFileName);
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
fileOutputStream.close();
fileInputStream.close();
After uploading the file you can find you file inside tomcat/webapps/ROOT/html/portlet
To get the source code link
Akira Akira, modificado hace 12 años.
RE: Using file upload in Liferay with Struts Portlet
Junior Member Mensajes: 80 Fecha de incorporación: 24/09/10 Mensajes recientes
Thanks Mani kandan
I success but name file image change.
I success but name file image change.
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(req);
File xxFile = uploadRequest.getFile("file");
String dirFileSave = config.getPortletContext().getRealPath("/")+"uploadedFiles/"+xxFile.getName();
try
{
byte[] bytes = FileUtil.getBytes(xxFile);
if ((bytes == null) || (bytes.length == 0))
{
dirFileSave = null;
}
if(FileUtil.exists(dirFileSave))
FileUtil.delete(dirFileSave);
File saveTo = new File(dirFileSave);
FileUtil.write(saveTo, bytes);
}
catch (Exception e)
{
System.out.print(e.toString());
dirFileSave = null;
}
Mani kandan, modificado hace 12 años.
RE: Using file upload in Liferay with Struts Portlet
Expert Mensajes: 492 Fecha de incorporación: 15/09/10 Mensajes recientes
I couldn't understand, Which one is changing?
Better you list out your error or example
Better you list out your error or example
Akira Akira, modificado hace 12 años.
RE: Using file upload in Liferay with Struts Portlet
Junior Member Mensajes: 80 Fecha de incorporación: 24/09/10 Mensajes recientes
when I submit path image "C:\Users\Skiatt\Desktop\buy1009\22.jpg""
>>> name image change >> C:\Users\Skiatt\Desktop\buy1009\upload_00000006.jpg
???????????
>>> name image change >> C:\Users\Skiatt\Desktop\buy1009\upload_00000006.jpg
???????????
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(req);
File xxFile = uploadRequest.getFile("file");
[color=#e20f0f]System.out.println(xxFile.getName());
System.out.println(xxFile.getPath());[/color]
String dirFileSave = config.getPortletContext().getRealPath("/")+"uploadedFiles/"+xxFile.getName();
try
{
byte[] bytes = FileUtil.getBytes(xxFile);
if ((bytes == null) || (bytes.length == 0))
{
dirFileSave = null;
}
if(FileUtil.exists(dirFileSave))
FileUtil.delete(dirFileSave);
File saveTo = new File(dirFileSave);
FileUtil.write(saveTo, bytes);
}
catch (Exception e)
{
System.out.print(e.toString());
dirFileSave = null;
}
Mani kandan, modificado hace 12 años.
RE: Using file upload in Liferay with Struts Portlet
Expert Mensajes: 492 Fecha de incorporación: 15/09/10 Mensajes recientes
See this is my ProcessAction method, I can able to upload the file without changing the file name.
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException
{
String realPath = getPortletContext().getRealPath("/");
byte[] bytes = null;
try{
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
String sourceFileName =uploadRequest.getFileName("fileName");
File file = uploadRequest.getFile("fileName");
try {
bytes = FileUtil.getBytes(file);
} catch (IOException e2) {
e2.printStackTrace();
}
File newFile=null;
if ((bytes != null) && (bytes.length > 0)) {
try {
newFile = new File(realPath+"html/portlet/"+sourceFileName);
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
fileInputStream.read(bytes);
fileOutputStream.write(bytes, 0, bytes.length);
fileOutputStream.close();
fileInputStream.close();
}
catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
}
catch (IOException e1){
System.out.println("Error Reading The File.");
e1.printStackTrace();
}
}
}
Akira Akira, modificado hace 12 años.
RE: Using file upload in Liferay with Struts Portlet
Junior Member Mensajes: 80 Fecha de incorporación: 24/09/10 Mensajes recientes
thanks Mani kandan
use
Good source code
use
String sourceFileName =uploadRequest.getFileName("fileName");
Good source code
Mani kandan, modificado hace 12 años.
RE: Using file upload in Liferay with Struts Portlet
Expert Mensajes: 492 Fecha de incorporación: 15/09/10 Mensajes recientes
You welcome
Satish Babu Anupoju, modificado hace 11 años.
RE: Using file upload in Liferay with Struts Portlet
Junior Member Mensajes: 79 Fecha de incorporación: 20/02/11 Mensajes recientes
Hi Mani
Can you please give me some suggestions . Below you can find the issue :
As per my requirement I have to create Parent folder( Doctor) under that multiple sub folders like (Physician, Dermitologist) under specific sub folders I have to upload image. that should be implement programatically.
I have done the implementation. Parent and first sub folder creating successfully. When I am creating another sub folder (Dynamically) it is throwing exception : DuplicateFolderNameException. I am passing the Folder name dynamically. So there is no chance to getting the duplicate name.
I hope you understand my requirement.
Below you can find the code :
JSP :
===
<portlet:actionURL var="fileUploadActionURL" name="fileUploadActionURL"></portlet:actionURL>
<form action="<%=fileUploadActionURL.toString() %>" method="post" enctype="multipart/form-data" >
<input id="my_file_element" type="file" name="<portlet:namespace />upload_file" />
<input type="submit" name="submit" value="Submit" />
</form>
ACTION :
========
public void processAction(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
UploadPortletRequest uploadRequest = PortalUtil
.getUploadPortletRequest(actionRequest);
File file = uploadRequest.getFile("upload_file");
String fileName = uploadRequest.getFileName("upload_file");
String[] splitString = fileName.split("_");
city = splitString[0];
location = splitString[1];
category = splitString[2];
sub_category = splitString[3];
String imageType = splitString[4];
String extension = splitString[5];
try {
ThemeDisplay display = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
User user = display.getUser();
long userId = user.getUserId();
Group group = GroupLocalServiceUtil.getGroup(display.getCompanyId(), GroupConstants.GUEST);
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(group.getGroupId());
//IGFolder cityIGFolder = IGFolderLocalServiceUtil.addFolder(userId, 0, city, "", serviceContext);
//IGFolder locationIGFolder = IGFolderLocalServiceUtil.addFolder(userId, cityIGFolder.getFolderId(), location, "", serviceContext);
IGFolder categoryIGFolder = IGFolderLocalServiceUtil.addFolder(userId, 0, category, "", serviceContext);
long categoryIGFolderId = categoryIGFolder.getFolderId();
IGFolder subCategoryIGFolder = IGFolderLocalServiceUtil.addFolder(userId, categoryIGFolderId, sub_category, "", serviceContext);
if("small".equalsIgnoreCase(imageType)){
System.out.println("SMALL IMAGE");
IGFolder smallIGFolder = IGFolderLocalServiceUtil.addFolder(userId, subCategoryIGFolder.getFolderId(), "SMALL", "", serviceContext);
System.out.println("small image folder id : "+smallIGFolder.getFolderId());
IGImageLocalServiceUtil.addImage(userId, group.getGroupId(), smallIGFolder.getFolderId(), fileName, "", file, "image/jpg", serviceContext);
} if("medium".equalsIgnoreCase(imageType)){
System.out.println("MEDIUM IMAGE");
IGFolder mediumIGFolder = IGFolderLocalServiceUtil.addFolder(userId, subCategoryIGFolder.getFolderId(), "MEDIUM", "", serviceContext);
System.out.println("Medium IG Folder ID :"+mediumIGFolder.getFolderId());
IGImageLocalServiceUtil.addImage(userId, group.getGroupId(), mediumIGFolder.getFolderId(), fileName, "", file, "image/jpg", serviceContext);
}if("big".equalsIgnoreCase(imageType)){
System.out.println("BIG IMAGE");
IGFolder bigIGFolder = IGFolderLocalServiceUtil.addFolder(userId, subCategoryIGFolder.getFolderId(), "BIG", "", serviceContext);
System.out.println("Big IG Folder ID :"+bigIGFolder.getFolderId());
IGImageLocalServiceUtil.addImage(userId, group.getGroupId(), bigIGFolder.getFolderId(), fileName, "", file, "image/jpg", serviceContext);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception in try");
}
}
PLEASE GIVE SOME SUGGESTIONS
Can you please give me some suggestions . Below you can find the issue :
As per my requirement I have to create Parent folder( Doctor) under that multiple sub folders like (Physician, Dermitologist) under specific sub folders I have to upload image. that should be implement programatically.
I have done the implementation. Parent and first sub folder creating successfully. When I am creating another sub folder (Dynamically) it is throwing exception : DuplicateFolderNameException. I am passing the Folder name dynamically. So there is no chance to getting the duplicate name.
I hope you understand my requirement.
Below you can find the code :
JSP :
===
<portlet:actionURL var="fileUploadActionURL" name="fileUploadActionURL"></portlet:actionURL>
<form action="<%=fileUploadActionURL.toString() %>" method="post" enctype="multipart/form-data" >
<input id="my_file_element" type="file" name="<portlet:namespace />upload_file" />
<input type="submit" name="submit" value="Submit" />
</form>
ACTION :
========
public void processAction(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
UploadPortletRequest uploadRequest = PortalUtil
.getUploadPortletRequest(actionRequest);
File file = uploadRequest.getFile("upload_file");
String fileName = uploadRequest.getFileName("upload_file");
String[] splitString = fileName.split("_");
city = splitString[0];
location = splitString[1];
category = splitString[2];
sub_category = splitString[3];
String imageType = splitString[4];
String extension = splitString[5];
try {
ThemeDisplay display = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
User user = display.getUser();
long userId = user.getUserId();
Group group = GroupLocalServiceUtil.getGroup(display.getCompanyId(), GroupConstants.GUEST);
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(group.getGroupId());
//IGFolder cityIGFolder = IGFolderLocalServiceUtil.addFolder(userId, 0, city, "", serviceContext);
//IGFolder locationIGFolder = IGFolderLocalServiceUtil.addFolder(userId, cityIGFolder.getFolderId(), location, "", serviceContext);
IGFolder categoryIGFolder = IGFolderLocalServiceUtil.addFolder(userId, 0, category, "", serviceContext);
long categoryIGFolderId = categoryIGFolder.getFolderId();
IGFolder subCategoryIGFolder = IGFolderLocalServiceUtil.addFolder(userId, categoryIGFolderId, sub_category, "", serviceContext);
if("small".equalsIgnoreCase(imageType)){
System.out.println("SMALL IMAGE");
IGFolder smallIGFolder = IGFolderLocalServiceUtil.addFolder(userId, subCategoryIGFolder.getFolderId(), "SMALL", "", serviceContext);
System.out.println("small image folder id : "+smallIGFolder.getFolderId());
IGImageLocalServiceUtil.addImage(userId, group.getGroupId(), smallIGFolder.getFolderId(), fileName, "", file, "image/jpg", serviceContext);
} if("medium".equalsIgnoreCase(imageType)){
System.out.println("MEDIUM IMAGE");
IGFolder mediumIGFolder = IGFolderLocalServiceUtil.addFolder(userId, subCategoryIGFolder.getFolderId(), "MEDIUM", "", serviceContext);
System.out.println("Medium IG Folder ID :"+mediumIGFolder.getFolderId());
IGImageLocalServiceUtil.addImage(userId, group.getGroupId(), mediumIGFolder.getFolderId(), fileName, "", file, "image/jpg", serviceContext);
}if("big".equalsIgnoreCase(imageType)){
System.out.println("BIG IMAGE");
IGFolder bigIGFolder = IGFolderLocalServiceUtil.addFolder(userId, subCategoryIGFolder.getFolderId(), "BIG", "", serviceContext);
System.out.println("Big IG Folder ID :"+bigIGFolder.getFolderId());
IGImageLocalServiceUtil.addImage(userId, group.getGroupId(), bigIGFolder.getFolderId(), fileName, "", file, "image/jpg", serviceContext);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception in try");
}
}
PLEASE GIVE SOME SUGGESTIONS
Jitendra Rajput, modificado hace 11 años.
RE: Using file upload in Liferay with Struts Portlet
Liferay Master Mensajes: 875 Fecha de incorporación: 7/01/11 Mensajes recientes
Every time you are trying add new folder with the same name using
What you can do is you can create required folders manually . And can get reference to created table by using their names .
IGFolderLocalServiceUtil.addFolder
.What you can do is you can create required folders manually . And can get reference to created table by using their names .
igFolder = IGFolderLocalServiceUtil.getFolder(groupId, 0, folderName);
Jitendra Rajput, modificado hace 12 años.
RE: Using file upload in Liferay with Struts Portlet
Liferay Master Mensajes: 875 Fecha de incorporación: 7/01/11 Mensajes recientes
Name of the uploaded file will be change ...that thing you have to manually take care ...
Vishal Panchal, modificado hace 11 años.
RE: Using file upload in Liferay with Struts Portlet
Expert Mensajes: 289 Fecha de incorporación: 20/05/12 Mensajes recientes
Hi,
This is good example of doing the same but using service.xml
link--> http://vforliferay.blogspot.in/2010/12/fileupload-using-servicexml-file.html
Thanks & Regards,
Vishal R. Panchal
This is good example of doing the same but using service.xml
link--> http://vforliferay.blogspot.in/2010/12/fileupload-using-servicexml-file.html
Thanks & Regards,
Vishal R. Panchal