Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
Clear All
new posts

    GWTUpload issue with Dynamic form

    Hi all,

    I have been pulling my hair out the last day trying to get GWTUpload working in my application.

    I have a Modal Popup window, which contains a form, there's a few text fields and then the GWTUpload component.

    Now after tinkering with the code for a day I have it in a working state. Issues's I has were with the upload button not appearing where I expected (and in fact I didn't want to use there button at all which API's say is possible by just passing in, didn't seem to function too well unfortunately) However I have fixed that issue by just removing the button GWTUpload adds.

    Next issue was that I wanted to select file via a hyper-link and for the filename to show in that text once select, that now works, I was just using wrong FileType, needed label.

    So that leaves me with the one remaining but biggest problem, I choose to use GWTUpload for the progress bar as this is something our users would like, but its just doesn't appear and I can't figure out what is going on, maybe its something to do with how its embedded in a DynamicForm, maybe I don't understand GWTUpload API's well enough, although everything I have read seems to suggest I should be seeing a progress bar.

    Code attached before, anyone got any views or guidance on what I'm doing wrong here that would be much appreciated

    Thanks
    Dale

    FYI, ModalFormWindow extends a window and adds a VLayout to it and then a Dynamic Form to the VLayout...
    SmartGWT Version 2.2

    Code:
    package com.serengetisystems.tcrm.client.window;
    
    import com.google.gwt.user.client.ui.Button;
    import com.serengetisystems.srgutils.marker.Reloadable;
    import com.serengetisystems.tcrm.client.util.DictionaryUtils;
    import com.serengetisystems.tcrm.client.widgets.ButtonBar;
    import com.serengetisystems.tcrm.client.widgets.button.CancelButton;
    import com.serengetisystems.tcrm.dto.detail.CaseDto;
    import com.serengetisystems.tcrm.dto.detail.CorrespondenceDto;
    import com.serengetisystems.tcrm.util.constants.DictionaryConstants;
    import com.smartgwt.client.types.Alignment;
    import com.smartgwt.client.widgets.Canvas;
    import com.smartgwt.client.widgets.IButton;
    import com.smartgwt.client.widgets.events.ClickEvent;
    import com.smartgwt.client.widgets.events.ClickHandler;
    import com.smartgwt.client.widgets.form.fields.*;
    import com.smartgwt.client.widgets.layout.VLayout;
    import gwtupload.client.*;
    
    /**
     * Document tab in case edit window use this to edit or add a new document
     *
     * @author: dale.ellis
     * Version History
     * -----------------------------------------------------------------------------------
     * Changed By     When        Description
     * dale.ellis     23/03/11    Initial release
     */
    public class AddEditDocumentWindow extends ModalFormWindow {
    
        private static final int POPUP_HEIGHT = 220;
        private static final int POPUP_WIDTH = 400;
    
        private CorrespondenceDto correspondence;
        private CaseDto caseObj;
        private Reloadable opener;
        private boolean isNew;
    
        // Form fields
        final private StaticTextItem createdDateField = new StaticTextItem();
        final private StaticTextItem createdByField = new StaticTextItem();
        final private TextItem descriptionField = new TextItem(DictionaryConstants.DESCRIPTION, DictionaryUtils.get(DictionaryConstants.DESCRIPTION));
    
        ButtonBar buttonBar = null;
        private final IButton saveButton = new IButton(DictionaryUtils.get(DictionaryConstants.SAVE));
        private final IButton cancelButton = new CancelButton();
    
    	private SingleUploader singleUploader;
    	private CanvasItem canvasItem;
    
    
        public AddEditDocumentWindow(final CorrespondenceDto correspondence, final CaseDto caseObj, Reloadable opener) {
            super(POPUP_WIDTH, POPUP_HEIGHT);
            this.correspondence = correspondence;
            this.caseObj = caseObj;
            this.opener = opener;
            isNew = (correspondence.getId() == null);
    
            setTitle((isNew ? DictionaryUtils.get(DictionaryConstants.ADD) : DictionaryUtils.get(DictionaryConstants.EDIT)) + " " + DictionaryUtils.get(DictionaryConstants.DOCUMENT));
    
            getForm().setNumCols(2);
            getForm().setColWidths("30%", "70%");
            getForm().setCellPadding(2);
            //getForm().setCellBorder(2);
            getForm().setHeight(this.getHeight() - 50);
    
            drawForm();
        }
    
        private void drawForm() {
            initFileUploadItem();
    
            if (!isNew) {
                createdDateField.setRequired(true);
                createdDateField.setTitle(DictionaryUtils.get(DictionaryConstants.CREATED_DATE));
                createdDateField.setTitleAlign(Alignment.LEFT);
                createdDateField.setValue(correspondence.getNote().getUserCreatedDate());
    
                createdByField.setRequired(true);
                createdByField.setTitle(DictionaryUtils.get(DictionaryConstants.CREATED_BY));
                createdByField.setTitleAlign(Alignment.LEFT);
                createdByField.setValue(correspondence.getNote().getCreatedBy().getName());
            }
            createdDateField.setVisible(!isNew);
            createdByField.setVisible(!isNew);
    
            SpacerItem spacer = new RowSpacerItem();
            spacer.setHeight(10);
    
            descriptionField.setRequired(true);
            descriptionField.setTitleAlign(Alignment.LEFT);
            descriptionField.setWidth("*");
            descriptionField.setValue(correspondence.getDescription());
    
            // BUTTONS
            buttonBar = new ButtonBar(Alignment.RIGHT, saveButton, cancelButton);
            saveButton.setDisabled(true);
            final CanvasItem buttonItems = new CanvasItem();
            buttonItems.setShowTitle(Boolean.FALSE);
            buttonItems.setColSpan(4);
            buttonItems.setHeight(20);
            buttonItems.setAlign(Alignment.RIGHT);
            VLayout buttonsItemLayout = new VLayout();
            buttonsItemLayout.addMember(buttonBar);
            buttonItems.setCanvas(buttonsItemLayout);
    
            getForm().setItems(createdDateField, createdByField, spacer, descriptionField, spacer, canvasItem, buttonItems);
    
            //GWTUpload uploader
            singleUploader.setServletPath(singleUploader.getServletPath() + "?caseId=" + caseObj.getId().toString());
            if (!isNew) {
                singleUploader.setServletPath(singleUploader.getServletPath() + "&correspondenceId=" + correspondence.getId().toString());
            }
    
            setupUploadHandler();
        }
    
        /**
         * Setup what happens when upload pressed
         */
        private void setupUploadHandler() {
            saveButton.addClickHandler(new ClickHandler() {
                @Override
                public void onClick(ClickEvent clickEvent) {
                    if (getForm().validate()) {
                        buttonBar.disableButtons();
                        singleUploader.setServletPath(singleUploader.getServletPath() + "&description=" + descriptionField.getValue().toString());
                        singleUploader.submit();
                    }
                }
            });
    
            cancelButton.addClickHandler(new ClickHandler() {
                @Override
                public void onClick(com.smartgwt.client.widgets.events.ClickEvent clickEvent) {
                    destroy();
                }
            });
        }
    
        /**
         * Create the GWTUpload field
         */
        //TODO status bar not showing, and use of own button failing
    	private void initFileUploadItem() {
    		canvasItem = new CanvasItem();
    		canvasItem.setWidth("*");
            canvasItem.setShowTitle(false);
            canvasItem.setColSpan(2);
            canvasItem.setHeight("25px");
    		Canvas canvas = new Canvas();
            Button button = new Button("Upload");
            singleUploader = new SingleUploader(IFileInput.FileInputType.LABEL, null, button);
            button.removeFromParent();
    		singleUploader.setWidth("100%");
    		singleUploader.setHeight("25px");
    		singleUploader.setAutoSubmit(false);
    		singleUploader.setEnabled(true);
    		// Add a finish handler which will load the image once the upload finishes
    		singleUploader.addOnFinishUploadHandler(onFinishUploaderHandler);
            singleUploader.addOnChangeUploadHandler(new IUploader.OnChangeUploaderHandler() {
                @Override
                public void onChange(IUploader uploader) {
                    saveButton.setDisabled(false);
                }
            });
    		canvas.addChild(singleUploader);
    		canvasItem.setCanvas(canvas);
    	}
    
        /**
         * Action to be called when upload has finished
         */
        private IUploader.OnFinishUploaderHandler onFinishUploaderHandler = new IUploader.OnFinishUploaderHandler() {
            public void onFinish(IUploader uploader) {
                if (uploader.getStatus() == IUploadStatus.Status.SUCCESS) {
                    opener.reload();
                    destroy();
                } else {
                    buttonBar.enableButtons();
                }
            }
        };
    
    }

    #2
    Hi,

    You might like to take a look at Apache fileUpload.

    Code:
    @Singleton
    @SuppressWarnings("serial")
    public class FileUploadServlet extends HttpServlet {
    
      @Override
      public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        this.process(request, response);
      }
    
      @Override
      public void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        this.process(request, response);
      }
    
      private void process(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    
        // check that we have a file upload request
        if (ServletFileUpload.isMultipartContent(request)) {
          processFiles(request, response);
        } else {
          processQuery(request, response);
        }
      }
    
      private File tmpDir;
      private static final String DESTINATION_DIR_PATH ="/files/upload";
      private File destinationDir;
    
      public void init(ServletConfig config) throws ServletException {
          super.init(config);
    
        DOMConfigurator.configure("log4j.xml");
    
        Log.debug("FileUpload Servlet");
    
        tmpDir = new File(((File) getServletContext().getAttribute("javax.servlet.context.tempdir")).toString());
    
        if (! tmpDir.isDirectory()) {
          throw new ServletException(tmpDir.toString() + " is not a directory");
        }
    
        Log.debug("tmpDir: " + tmpDir.toString());
    
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
    
        if (! destinationDir.isDirectory()) {
          throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        }
    
        Log.debug("destinationDir: " + destinationDir.toString());
      }
    
      @SuppressWarnings("unchecked")
      private void processFiles(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    
        // create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
    
        // set the size threshold, above which content will be stored on disk
        factory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
    
        // set the temporary directory (this is where files that exceed the threshold will be stored)
        factory.setRepository(tmpDir);
    
        // create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
    
        try {
          String recordType = "Account";
    
          // parse the request
          List items = upload.parseRequest(request);
    
          // process the uploaded items
          Iterator itr = items.iterator();
    
          while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
    
            // process a regular form field
            if (item.isFormField()) {
              Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getString());
    
              if (item.getFieldName().equals("recordType")) {
                recordType = item.getString();
              }
            } else {
              // process a file upload
              Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getName() +
                ", Content Type: "+ item.getContentType() + ", In Memory: " + item.isInMemory() +
                ", File Size: " + item.getSize());
    
              // write the uploaded file to the application's file staging area
              File file = new File(destinationDir, item.getName());
              item.write(file);
    
              importCsvFile(recordType, file.getPath());
            }
          }
        }
        catch (FileUploadException e) {
          Log.error("Error encountered while parsing the request", e);
        }
        catch (Exception e) {
          Log.error("Error encountered while uploading file", e);
        }
      }
    And take a look at this post -> http://forums.smartclient.com/showthread.php?t=5477 and this post -> http://forums.smartclient.com/showthread.php?t=5477&page=2

    Code:
      ...
    
      private static final String DEFAULT_FILE_UPLOAD_SERVICE_PATH = "upload";
      private static final String RECORD_TYPE = "recordType";
      private static final String MAP_NAME = "mapName";
      private static final String TARGET="uploadTarget";
    
      private VLayout initBody() {
    
        // initialise the Footer layout container
        VLayout body = new VLayout();
        body.setStyleName("crm-Wizard-Body");
        body.setWidth100();
        body.setHeight100();
    
        // initialise the form
        uploadForm = new DynamicForm();
        uploadForm.setWidth100();
        uploadForm.setMargin(8);
        uploadForm.setNumCols(2);
        uploadForm.setCellPadding(2);
        uploadForm.setWrapItemTitles(false);
        // no ":" after the field name
        uploadForm.setTitleSuffix(" ");
        uploadForm.setRequiredTitleSuffix(" ");
    
        // initialise the hidden frame
        NamedFrame frame = new NamedFrame(TARGET);
        frame.setWidth("1px");
        frame.setHeight("1px");
        frame.setVisible(false);
    
        uploadForm.setEncoding(Encoding.MULTIPART);
        uploadForm.setMethod(FormMethod.POST);
        // set the (hidden) form target
        uploadForm.setTarget(TARGET);
    
        StringBuilder url = new StringBuilder();
        url.append(DEFAULT_FILE_UPLOAD_SERVICE_PATH);
        uploadForm.setAction(FileUploadEntryPoint.getRelativeURL(url.toString()));
    
        // initialise the Record type field
        recordType = new ComboBoxItem(RECORD_TYPE, "Record type");
        recordType.setName(RECORD_TYPE);
        recordType.setType("comboBox");
        recordType.setValueMap("Account", "Contact");
        recordType.setDefaultToFirstOption(true);
        recordType.setSelectOnFocus(true);
    
        // initialise the Map field
        mapName = new ComboBoxItem(MAP_NAME, "Data map");
        mapName.setName(MAP_NAME);
        mapName.setType("comboBox");
        mapName.setValueMap("Automatic", "Create new map");
        mapName.setDefaultToFirstOption(true);
    
        // initialise the File name field
        uploadItem = new UploadItem("filename");
        uploadItem.setName("filename");
        uploadItem.setTitle("File name");
        uploadItem.setWidth(280);
    
        // set the fields into the form
        uploadForm.setFields(recordType, mapName, uploadItem);
    
        body.addMember(uploadForm);
        body.addMember(frame);
    
        return body;
      }
    Cheers
    Rob
    Attached Files

    Comment

    Working...
    X