Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: File Uploading not working

  1. #1
    Junior Member
    Join Date
    Aug 2017
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default File Uploading not working

    Hello all, this is my first post here to here goes...

    On my index.class servlet I have the following code:

     
    else if(ServletFileUpload.isMultipartContent(request)){
     
                nwg = new NWG(session.getAttribute("authenticated")!=null?session.getAttribute("authenticated").toString():null);
                Map<String, String> formData = this.formDataToHashMap(request);
     
                FileUploader file = new FileUploader(request);
                file.saveToRelativePath("users\\evo4ever\\images\\");
                String message = null;
     
                if(file.upload()) message = "File uploaded ";
     
                FormController doForm = new FormController(formData.get("FORM_SUBMIT"), formData);
                doForm.SwitchFormProcess();
     
                request.setAttribute("message", message+doForm.getMessage());
                request.setAttribute("nwg", nwg);
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }

    the this.formDataToHashMap(request) method is as follows:

     
    private Map<String, String> formDataToHashMap(HttpServletRequest request) {
     
    		Map<String, String> formData = new HashMap<String, String>();
     
    		if(ServletFileUpload.isMultipartContent(request)) {
     
    			DiskFileItemFactory factory = new DiskFileItemFactory();
    		    ServletFileUpload upload = new ServletFileUpload(factory);
     
    			try {
     
    				List fileItems = upload.parseRequest(request);
    		        Iterator i = fileItems.iterator();
     
    				while(i.hasNext()) {
     
    					FileItem fi = (FileItem)i.next();
     
    					if(fi.isFormField()) {
     
    						formData.put(fi.getFieldName(), fi.getString());
    					}
    				}
    			}
    			catch(Exception e) {
     
    				return null;
    			}
    		}
    		else {
     
    			Enumeration params = request.getParameterNames();
     
    			while(params.hasMoreElements()) {
     
    				String paramName = (String)params.nextElement();
     
    				if(!paramName.equals("FORM_SUBMIT")) {
     
    					formData.put(paramName, request.getParameter(paramName));
    				}
    			}
    		}
     
    		return formData;
    	}

    And my FileUploader.class code:

     
    package evo.net;
     
    import java.io.*;
    import java.util.*;
     
    import javax.servlet.http.HttpServletRequest;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.io.output.*;
     
    public class FileUploader {
     
        private String path = "D:\\Apache Software Foundation\\Tomcat 7.0\\webapps\\ROOT\\";
        private String saveToDir = null;
        private int maxFileSize = 2147483500;
        private int maxMemSize = 4 * 1024;
        private File file;
     
        private HttpServletRequest request;
        private String message;
     
        public FileUploader(HttpServletRequest request) {
     
            this.request = request;
        }
     
        public void setMaxFileSize(int size) {
     
            this.maxFileSize = size;
        }
     
        public void setMaxMemSize(int size) {
     
            this.maxMemSize = size;
        }
     
        public void saveToRelativePath(String path) {
     
            this.saveToDir = this.path+path;
        }
     
        public void saveToAbsolutePath(String path) {
     
            this.path = path;
        }
     
        public String getMessage() {
     
            return this.message;
        }
     
        public boolean upload() {
     
            String saveTo = null;
     
            if(this.saveToDir!=null) saveTo = this.saveToDir;
            else saveTo = this.path;
     
            if(ServletFileUpload.isMultipartContent(this.request)) {
     
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(this.maxMemSize);
                factory.setRepository(new File(this.path));
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(this.maxFileSize);
     
                try {
     
                    List fileItems = upload.parseRequest(this.request);
                    Iterator i = fileItems.iterator();
     
                     while(i.hasNext()) {
     
                         FileItem fi = (FileItem)i.next();
     
                         if(!fi.isFormField()) {
     
                            String fieldName = fi.getFieldName();
                            String fileName = fi.getName();
                            String contentType = fi.getContentType();
                            boolean isInMemory = fi.isInMemory();
                            long sizeInBytes = fi.getSize();
     
                            if(fileName.lastIndexOf("\\") >= 0 ) {
     
                             file = new File(saveTo + fileName.substring(fileName.lastIndexOf("\\"))) ;
                            } 
                            else {
     
                                file = new File(saveTo + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
                            }
     
                              fi.write(file);
                         }
                     }
                }
                catch(Exception ex) {
     
                    this.message = " File Upload Error: "+ex.getMessage();
                    return false;
                }
            }
     
            return true;
        }
    }

    When I create an object of FileUploader in my index servlet the file wont upload which throws no exceptions, and nor do does it have any compile time errors.

    However, If I create a test servlet called fupload, code as follows:

     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
     
            if(ServletFileUpload.isMultipartContent(request)) {
     
                FileUploader file = new FileUploader(request);
                file.saveToRelativePath("users\\evo4ever\\images\\");
     
                if(file.upload()) out.println("File successfully uploaded.");
                else out.println(file.getMessage());
            }
            else out.println("No multipart content!");
        }

    The file will upload as expected with no errors or exceptions of any kind. The problem is why would it work in one servlet (fuploader) and not in another (index servlet)? Thats what I cant get my head around because clearly the FileUploader works but only when it feels like lol.

    I'm suspecting its not working because ive already processed the request object. So I change the index.class servlet for experimental purposes to this:

     
    else if(ServletFileUpload.isMultipartContent(request)){
     
                nwg = new NWG(session.getAttribute("authenticated")!=null?session.getAttribute("authenticated").toString():null);
     
                //Map<String, String> formData = this.formDataToHashMap(request);
     
                String message = null;
     
                FileUploader file = new FileUploader(request);
                file.saveToRelativePath("users\\evo4ever\\images\\");
     
                if(file.upload()) message = "File successfully uploaded.";
                else message = file.getMessage();
     
                //FormController doForm = new FormController(formData.get("FORM_SUBMIT"), formData);
                //doForm.SwitchFormProcess();
     
                request.setAttribute("message", message);
                request.setAttribute("nwg", nwg);
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }

    As you can see ive commented out the FormController object and now the file WILL upload! Any explanations as to why its doing this? Is there anyway of creating two separate request objects? one for processing the form data and one for processing the file/s? Cheers guys and this is ripping my hair out lol.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,778
    Thanks
    50
    Thanked 2,238 Times in 2,210 Posts

    Default Re: File Uploading not working

    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Aug 2017
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: File Uploading not working

    Quote Originally Posted by Norm View Post
    Yeah thats my post but i cant get a response from anyone..

Similar Threads

  1. Simple Ftp server for uploading and downloading file
    By eku in forum What's Wrong With My Code?
    Replies: 11
    Last Post: January 25th, 2014, 11:00 AM
  2. Uploading File to server ( Apache.commons.net)
    By quirell in forum Java Networking
    Replies: 5
    Last Post: November 11th, 2012, 10:06 PM
  3. Help me out with code for uploading saved file in perticular format
    By sweet_guy5914 in forum Java Theory & Questions
    Replies: 1
    Last Post: September 18th, 2012, 06:30 PM
  4. multiple file uploading and downloading
    By priti in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 27th, 2012, 11:34 AM
  5. Uploaded file getting saved to Bin directory
    By jazz2k8 in forum JavaServer Pages: JSP & JSTL
    Replies: 1
    Last Post: July 13th, 2008, 01:59 PM

Tags for this Thread