GWT上传小部件-将POST的查询字符串附加到servlet类

时间:2018-12-19 15:35:08

标签: java servlets gwt

我正在使用上载小部件来上载文件。我创建了一个servlet类来获取文件。一切正常。我想做的是将一个字符串附加到表单发布,以便我可以在servlet doPost方法中在服务器端检索它。

是否可以将查询字符串与文件上传一起附加到表单? 如果可以,怎么办?

如果可能的话,我想在提交表单之前附加accountIdStr。

这是客户端表单

           this.userAccount = userAccount;
        allAccounts = new LinkedHashMap<>();

        accounts = new ListBox();
        accounts.setName("accounts");

        addStyleName("InviteUsersPanel");
        setCellSpacing(10);

        VerticalPanel panel = new VerticalPanel();
        panel.add(accounts);

        final FormPanel form = new FormPanel();
        form.setEncoding(FormPanel.ENCODING_MULTIPART);
        form.setMethod(FormPanel.METHOD_POST);


        Label lb2 = new Label("Select file");
        upload = new FileUpload();
        upload.setName("upload");
        upload.setEnabled(false);

        VerticalPanel holder = new VerticalPanel();
        holder.add(lb2);
        holder.add(upload);


        uploadButton = new Button("Import");
        uploadButton.setEnabled(false);

        uploadButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                String filename = upload.getFilename();
                if (filename.length() == 0) {
                    Window.alert("No File Specified!");
                } else {
                    int selectedIndex = accounts.getSelectedIndex();
                    String accountIdStr = accounts.getValue(selectedIndex);

                    //set the query string here????
                    form.submit();
                }
            }
        });

        holder.add(uploadButton);


        accounts.addChangeHandler(new ChangeHandler() {
            public void onChange(ChangeEvent event) {
                SelectorState.global().setSelectedAccountId(getSelectedAccountId());
              //  loadUsers(true);
            }
        });

        form.add(holder);
        panel.add(form);

        form.setAction(GWT.getModuleBaseURL()+"uploadfile");

        form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
            @Override
            public void onSubmitComplete(FormPanel.SubmitCompleteEvent event) {

                if(!event.getResults().equalsIgnoreCase("")) {
                    Window.alert(event.getResults());
                }
            }
        });

        setWidget(0,0,panel);
        getCellFormatter().addStyleName(0, 0, "formCell");
        getCellFormatter().setVerticalAlignment(0, 1, HasVerticalAlignment.ALIGN_TOP);

         loadAccounts();

    }

这是服务器端servlet

public class FileUpload extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {

    long maxFileSize = 20480;
    long sizeInBytes = 0;
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);


   Object b = request.getSession().getAttribute("UZERACCOUNT_ID");
    int i = (Integer) b;

   // get the string here????
   String m = request.getQueryString();


    try {

        List items = upload.parseRequest(request);

        Iterator iter = items.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            //handling a normal form-field
            if(item.isFormField()) {
                System.out.println("Got a form field");
                String name = item.getFieldName();
                String value = item.getString();
                System.out.print("Name:"+name+",Value:"+value);

            } else {

                //handling file loads
                System.out.println("Not form field");
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                 sizeInBytes = item.getSize();
                 if("image/png".equalsIgnoreCase(contentType) || "image/jpeg".equalsIgnoreCase(contentType)){

                 } else{
                     throw new RuntimeException("Only images with file extension .jpg and .png are allowed" );
                }

                if (sizeInBytes >= maxFileSize) {
                    throw new RuntimeException("File is bigger than 20kb allowed. Please upload an image thats 20kb or less" );
                } else {

                    byte[] data = item.get();
                }

            }
        }

编辑,我认为我过早地发表了这篇文章。我能够做到,但是在提交它之前将其添加为查询字符串:

form.setAction(GWT.getModuleBaseURL()+"uploadfile" + "?entityId="+ accountIdStr);

1 个答案:

答案 0 :(得分:0)

根据Java文档FormPanel,它接受​​Hidden UI类型。

我还没有测试过,但是我会考虑这样的事情:

final FormPanel form = new FormPanel();
final Hidden accountIdStrFormElement = new Hidden("accountIdStr");
form.add(accountIdStrFormElement);

// later
accountIdStrFormElement.setValue(accountIdStr);
form.submit();

这最终将与您的查询字符串技巧完全相同,但这将更具编程性,并且可能使您可以重用更多代码,更轻松地进行调试等。