473,416 Members | 1,536 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 software developers and data experts.

Getting File in Server Program but not uploding it...Need help

HI friends,

I am using the Flex to upload files to server. I m getting all the details about the file, but I m not able to upload it to Server. Here is the code i m using for both flex & for Struts:

Expand|Select|Wrap|Line Numbers
  1. import java.io.File;
  2. import java.io.PrintWriter;
  3. import java.util.ArrayList;
  4. import java.util.Enumeration;
  5. import java.util.Iterator;
  6. import java.util.List;
  7.  
  8. import javax.servlet.ServletContext;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11.  
  12. import org.apache.commons.fileupload.FileItem;
  13. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  14. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  15. import org.apache.struts.action.Action;
  16. import org.apache.struts.action.ActionForm;
  17. import org.apache.struts.action.ActionForward;
  18. import org.apache.struts.action.ActionMapping;
  19.  
  20. public class ServerFileUpload extends Action {
  21.     @Override
  22.     public ActionForward execute(ActionMapping mapping, ActionForm form, 
  23.             HttpServletRequest request, HttpServletResponse response) throws Exception {
  24.         try {
  25.             DiskFileItemFactory factory = new DiskFileItemFactory();
  26.             ServletFileUpload upload = new ServletFileUpload(factory);
  27.             /*
  28.              * both file size & attachments size should not be greater than 10MB.
  29.              */
  30.             upload.setFileSizeMax(10*1024*1024);
  31.             upload.setSizeMax(10*1024*1024);
  32.             List items = upload.parseRequest(request);            
  33.             Enumeration e = request.getParameterNames();
  34.             while(e.hasMoreElements()){
  35.                 System.out.println("Parameter Name are "+e.nextElement());
  36.             }
  37.  
  38.             Iterator iter = items.iterator();
  39.             List lstFiles = new ArrayList();
  40.             while (iter.hasNext()) {
  41.                 FileItem item = (FileItem) iter.next();
  42.                 System.out.println("in while");
  43.  
  44.                 if (!item.isFormField()) {
  45.                     String fieldName = item.getFieldName();
  46.                     System.out.println("Field Name is :" + fieldName);
  47.                     String filePath = item.getName();
  48.                     System.out.println(filePath);
  49.                     long size = item.getSize();
  50.                     System.out.println("The size of the File is : "+size);
  51.  
  52.                     if(filePath.equals(""))
  53.                         continue;
  54.  
  55.                     String contentType = item.getContentType();  
  56.                     System.out.println("The File Content Type Are "+contentType);
  57.  
  58.                     ServletContext ctx = getServlet().getServletContext();
  59.  
  60.                     String folder  = ctx.getRealPath("WEB-INF/uploadedfiles/" +fieldName);                    
  61.  
  62.                     System.out.println("real path "+folder);
  63.                     File f=new File(folder);
  64.                     if(!f.exists()){
  65.                         System.out.println("Folder Does Not Exit");
  66.                         f.mkdir();
  67.                     }
  68.                     File file = new File(filePath);
  69.                     boolean status= file.renameTo(new File(folder, file.getName())); 
  70.                     System.out.println("Copy Status is "+status);                       
  71.  
  72.                    // System.out.println(folder + "/" + file);
  73.  
  74.                     File uploadedFile = new File(filePath);
  75.                     item.write(uploadedFile);                    
  76.                     lstFiles.add(filePath);
  77.                 }
  78.             }            
  79.             PrintWriter out = response.getWriter();
  80.             response.setContentType("text/xml");            
  81.             out.print("<result>success</result>");            
  82.         } catch (Exception e) {
  83.             System.out.println("Exception in FileUpload"+e.getMessage());
  84.         }
  85.         return null;
  86.     }
  87. }
  88.  

here is the flex code:

Expand|Select|Wrap|Line Numbers
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="initApp()">
  3.     <mx:Script>
  4.     <![CDATA[
  5.         import mx.controls.Alert;
  6.         import mx.utils.ObjectUtil;
  7.         import flash.events.*;
  8.         import flash.net.FileReference;
  9.         import flash.net.URLRequest;
  10.  
  11.  
  12.         private var fileRef:FileReference;
  13.  
  14.         private function initApp():void {            
  15.             fileRef = new FileReference();
  16.             fileRef.addEventListener(Event.CANCEL, traceEvent);
  17.             fileRef.addEventListener(Event.COMPLETE, completeEvent);
  18.             fileRef.addEventListener(Event.SELECT, selectEvent);
  19.             fileRef.addEventListener(IOErrorEvent.IO_ERROR, traceEvent);
  20.             fileRef.addEventListener(Event.OPEN, traceEvent);
  21.             fileRef.addEventListener(ProgressEvent.PROGRESS, progressEvent);
  22.             fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, traceEvent);
  23.         }
  24.  
  25.         private function traceEvent(event:Event):void {
  26.             var tmp:String = "================================\n";
  27.             ta.text += tmp + event.type + " event:" + mx.utils.ObjectUtil.toString(event) + "\n" ;
  28.             ta.verticalScrollPosition += 20;
  29.         }
  30.  
  31.         private function ioErrorEvent(event:IOErrorEvent):void{
  32.             Alert.show("IOError:" + event.text);
  33.             traceEvent(event);
  34.         }
  35.  
  36.         private function selectEvent(event:Event):void{
  37.             btn_upload.enabled = true;
  38.             traceEvent(event);
  39.             filename.text = fileRef.name;
  40.  
  41.             progressBar.setProgress(0, 100);
  42.             progressBar.label = "Loading 0%";            
  43.         }
  44.  
  45.         private function progressEvent(event:ProgressEvent):void {
  46.             progressBar.setProgress(event.bytesLoaded, event.bytesTotal);
  47.             traceEvent(event);
  48.         }
  49.  
  50.         private function completeEvent(event:Event):void {
  51.             progressBar.label = "Complete.";
  52.             filename.text += " uploaded";
  53.             traceEvent(event);
  54.             btn_upload.enabled = false;
  55.             btn_cancel.enabled = false;
  56.         }
  57.  
  58.         private function uploadFile(endpoint:String):void {
  59.             var param:String = "Ashish";
  60.             var req:URLRequest = new URLRequest(endpoint);
  61.             req.method = URLRequestMethod.POST;
  62.             fileRef.upload(req, param, false); 
  63.             progressBar.label = "Uploading...";        
  64.             btn_cancel.enabled = true;
  65.         }
  66.  
  67.     ]]>
  68.     </mx:Script>
  69.  
  70.     <mx:Panel title="Flex 2 File Uploading Demo" width="100%" height="100%" >
  71.         <mx:Form>
  72.  
  73.             <mx:FormItem label="Upload URL:" id="uploadurl">
  74.                 <mx:TextInput id="uploadURL" width="100%" text="http://localhost:8080/visionmail/upload.do" enabled="true"  />
  75.             </mx:FormItem>
  76.  
  77.             <mx:FormItem label="Selected File:" id="frmfilename">
  78.                 <mx:Label id="filename"/>
  79.             </mx:FormItem>
  80.  
  81.             <mx:FormItem label="Upload By:" id="author">
  82.                 <mx:TextInput id="ti_author" text="Author" />
  83.             </mx:FormItem>
  84.  
  85.             <mx:FormItem direction="horizontal" width="100%">
  86.                 <mx:Button width="80" label="Browse" click="fileRef.browse()" />
  87.                 <mx:Button width="80" label="Upload" id="btn_upload" enabled="false" click="uploadFile(uploadURL.text)" />
  88.                 <mx:Button width="80" label="Cancel" id="btn_cancel" enabled="false" click="fileRef.cancel()" />
  89.             </mx:FormItem>
  90.  
  91.             <mx:HRule width="100%" tabEnabled="false"/>
  92.  
  93.             <mx:FormItem label="Progress:">
  94.                 <mx:ProgressBar id="progressBar" mode="manual" />
  95.             </mx:FormItem>
  96.  
  97.             <mx:FormItem label="Events:">
  98.                 <mx:TextArea id="ta" width="350" height="200" />
  99.             </mx:FormItem>
  100.  
  101.         </mx:Form>
  102.  
  103.     </mx:Panel>    
  104. </mx:Application>
  105.  
  106.  
can somebody tell me what is the problem here.
May 22 '07 #1
4 6189
kestrel
1,071 Expert 1GB
Thats not the way it works around here. I'm sorry but its not our job to find out whats wrong with your code. Normally, people resent us with their error and a partial bit of code (not the full thing) and we help them our and/or point them in the right direction so that they may solve the problem themselves. Are there any specific problems you have?
May 22 '07 #2
Thats not the way it works around here. I'm sorry but its not our job to find out whats wrong with your code. Normally, people resent us with their error and a partial bit of code (not the full thing) and we help them our and/or point them in the right direction so that they may solve the problem themselves. Are there any specific problems you have?

Problem is
List items = upload.parseRequest(request);
returning empty list.

When same code is used in JSP it work fine. Problem is when URL is struts action. Then in the action class i am not able to get the contents.
Aug 21 '08 #3
elay
3
I want to upload a file using action script & servlet to a server?

I am new to action script & i don't know where to start.

please guide me...

Thanks
Nov 24 '08 #4
Dear vijendrahs ,

I am also facing same problem exactly... kindly if u found the solution for it.. please share with me...

Thanks and Regards
Diny Jayas
Jul 2 '09 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: PHPkemon | last post by:
Hi there, A few weeks ago I made a post and got an answer which seemed very logical. Here's part of the post: PHPkemon wrote: > I think I've figured out how to do the main things like...
1
by: Carolyn Speakman | last post by:
Hi, I need to get a directory listing from a client machine. The directory will be specified by the user and the results will be stored on the server in an xml file. I've been trying to use the...
7
by: CG | last post by:
I am looking for a way to parse a simple log file to get the information in a format that I can use. I would like to use python, but I am just beginning to learn how to use it. I am not a...
5
by: Grace | last post by:
Hello, I want to upload the file by webpage to SQL Server. When I upload the small file, it is work. But, when I upload big file(ex. 40~50 MB), it isn't work; the Browser displays the...
8
by: Sarah | last post by:
I need to access some data on a server. I can access it directly using UNC (i.e. \\ComputerName\ShareName\Path\FileName) or using a mapped network drive resource (S:\Path\FileName). Here is my...
0
by: ruju00 | last post by:
I am getting an error in Login() method of the following class FtpConnection public class FtpConnection { public class FtpException : Exception { public FtpException(string message) :...
41
by: LayneMitch via WebmasterKB.com | last post by:
I was just chating with a few webdevelopers and it was brought to my attention that I need some type of server technology installed on my computer so I could get a visual of how my sites would look...
0
by: shalureddy | last post by:
Hi , I have installed Forefront Security for sharepoint srever.During Configuration when I try to upload .com file it is displaying error mmsg(Working Properly). When I rename that file to...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.