1. #1
    Sencha User
    Join Date
    Jul 2009
    Posts
    4
    Vote Rating
    0
    willbrady is on a distinguished road

      0  

    Default FileUploadField example

    FileUploadField example


    Does anyone have a working example of using the FileUploadField to upload a file to a servlet? I can send the path name of the file to the servlet, but what is the right way to actually upload the file?

    All ideas are welcomed!

  2. #2
    Sencha User
    Join Date
    Apr 2008
    Posts
    133
    Vote Rating
    0
    FireGlow is on a distinguished road

      0  

    Default


    hey!

    having the same problem!

    I wrote an Servlet, but it only delivres the name of the file!

    Code:
    public class ArchetypeUploadServlet extends HttpServlet {
    
        private ArchetypeService archetypeService;
    
        public final String TEMP_UPLOAD_FOLDER = "D:/server/temp/";
    
        public ArchetypeUploadServlet() {
        super();
    
        }
    
        public void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException {
        }
    
        /**
         * Takes the upload request and uploads the file
         */
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        PrintWriter out = resp.getWriter();
        try {
            archetypeService = ArchetypeServiceImpl.getInstance();
            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> fileItems = upload.parseRequest(req);
    
            Iterator it = fileItems.iterator();
            File uploadedFile;
            while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            GregorianCalendar tempDate = new GregorianCalendar();
            uploadedFile = new File(TEMP_UPLOAD_FOLDER + tempDate.getTimeInMillis() + ".adl");
    
            item.write(uploadedFile);
    
            User user = (User) req.getSession().getAttribute(User.USER_LOGGED_IN);
            if (user == null) {
                throw new AccessControlException("No user found in the session.");
            }
            archetypeService.importArchetype(uploadedFile, user);
            out.println("success");
    
            }
    
        } catch (Exception e) {
            out.println("failed");
        }
    
        }
    }

  3. #3
    Ext User
    Join Date
    Jul 2009
    Posts
    25
    Vote Rating
    0
    silv is on a distinguished road

      0  

    Default


    I think you need to check if the item is a form field. if(item.isFormField())

  4. #4
    Sencha User
    Join Date
    Jun 2011
    Location
    Iasi, Romania
    Posts
    144
    Vote Rating
    0
    catalin.ciobanu is on a distinguished road

      0  

    Default


    Have you get this working anyhow ? I'd be interested what was the problem and most of it, the way you solved it.

  5. #5
    Sencha User
    Join Date
    Jul 2009
    Posts
    4
    Vote Rating
    0
    willbrady is on a distinguished road

      0  

    Default


    I haven't looked at this in years and never got what I was trying to do working

  6. #6
    Sencha User
    Join Date
    Jun 2011
    Location
    Iasi, Romania
    Posts
    144
    Vote Rating
    0
    catalin.ciobanu is on a distinguished road

      0  

    Default


    Yeah I figured it out. Thanks.

  7. #7
    Sencha User
    Join Date
    Jan 2011
    Posts
    1
    Vote Rating
    0
    rvanker is on a distinguished road

      0  

    Default example ?

    example ?


    Can you provide an example (client, servlet code and web.xml) ?

  8. #8
    Sencha User
    Join Date
    Jun 2011
    Location
    Iasi, Romania
    Posts
    144
    Vote Rating
    0
    catalin.ciobanu is on a distinguished road

      0  

    Default


    well, client side:
    Code:
    public class UploadPopup extends Popup {
    
        private static String UPLOAD_ACTION_URL = "";
    
        public UploadPopup(String id) {
            // insert_id = the id of the parent
            // String mess = GWT.getHostPageBaseURL().substring(0,
            // GWT.getHostPageBaseURL().lastIndexOf("/"));
            UPLOAD_ACTION_URL = servletAddress          //replace this
                    + "/FileServlet/events?insert_id=" + id;
        }
    
        @Override
        protected void onRender(Element target, int index) {
            super.onRender(target, index);
            final ContentPanel cp = new ContentPanel();
    
            cp.setHeaderVisible(false);
            final FormPanel form = new FormPanel();
    
            // set the encoding and the method to submit the form
            form.setEncoding(FormPanel.ENCODING_MULTIPART);
            form.setMethod(FormPanel.METHOD_POST);
    
            // set the address of the action
            form.setAction(UPLOAD_ACTION_URL);
            ContentPanel holder = new ContentPanel();
            holder.setHeaderVisible(false);
    
            final FileUpload upload = new FileUpload();
            upload.setName("upload");
            holder.add(upload);
    
            holder.add(new Button("Submit", new ClickListener() {
                public void onClick(Widget sender) {
                    form.submit();
                    cp.hide();
                }
            }));
    
            form.add(holder);
            form.addFormHandler(new FormHandler() {
                public void onSubmit(FormSubmitEvent event) {
                    if (upload.getFilename().length() == 0) {
                        Window.alert("Select a file to upload.");
                        event.setCancelled(true);
                    }
                }
    
                public void onSubmitComplete(FormSubmitCompleteEvent event) {
                    FilesTree.refresh();
                }
            });
            cp.add(form);
            cp.setPosition(-100, -100);
            add(cp);
        }
    
    }
    Server side (i do it on doPost method)
    Code:
    // if the event is an insert event
            if (req.getParameter("insert_id") != null) {
                String parentId = req.getParameter("insert_id");
                String parentPath = null;
                try {
                    parentPath = DBUtil.getPath(parentId) + "/";
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                // process only multipart requests
                if (ServletFileUpload.isMultipartContent(req)) {
    
                    // Create a factory for disk-based file items
                    FileItemFactory factory = new DiskFileItemFactory();
    
                    // Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(
                            (org.apache.commons.fileupload.FileItemFactory) factory);
    
                    // Parse the request
                    try {
                        List<FileItem> items = upload.parseRequest(req);
                        for (FileItem item : items) {
                            // process only file upload - discard other form item
                            // types
                            if (item.isFormField())
                                continue;
    
                            String fileName = item.getName();
                            // get only the file name not whole path
                            if (fileName != null) {
                                fileName = FilenameUtils.getName(fileName);
                            }
    
                            // create a new file
                            File uploadedFile = new File(parentPath, fileName);
                            if (uploadedFile.createNewFile()) {
                                item.write(uploadedFile);
                                resp.setStatus(HttpServletResponse.SC_CREATED);
                                resp.getWriter().print(
                                        "The file was uploaded successfully.");
                                resp.flushBuffer();
    
                                // update the database
                                boolean updateDB = DBUtil.updateDB(parentId, 0,
                                        fileName, parentPath + fileName);
                                if (!updateDB) {
                                    // something's wrong
                                    resp.sendError(
                                            HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                            "An error occured while updating the database!");
                                }
                            } else
                                throw new IOException("The file already exists.");
                        }
                    } catch (Exception e) {
                        resp.sendError(
                                HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "An error occurred while creating the file : "
                                        + e.getMessage());
                    }
    
                } else {
                    resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                            "Request contents type is not supported by the servlet.");
                }
            }
    i use (on server side ofc)
    -commons-fileupload-1.2.2.jar
    -commons-io-2.0.1.jar
    I don't remember if I needed both but I see them on ../lib so it might be required

    I keep some records in a database also .. about my files, that's why there's some database update ..