【问题标题】:Form action didn't rest after downloading file with servlets in GWT?在 GWT 中下载带有 servlet 的文件后,表单操作没有休息?
【发布时间】:2016-05-05 20:54:44
【问题描述】:

我在GWT中开发了一个小应用程序,在进行一些操作后上传和下载文件,它工作正常,但是文件下载后加载对话框图像永远不会停止,请指教。

客户端代码

public class Firstmodule implements EntryPoint
{


public void onModuleLoad()
{

    final PopupPanel popup = new PopupPanel(false, true); // Create a modal dialog box that will not auto-hide


    final FileUpload fileUpload = new FileUpload();
    final FormPanel form = new FormPanel();
    VerticalPanel vPanel = new VerticalPanel();
    Image img = new Image("download.png");
    vPanel.add(img);

    form.setMethod(FormPanel.METHOD_POST);
    // The HTTP request is encoded in multipart format.
    form.setEncoding(FormPanel.ENCODING_MULTIPART); 

    form.setTitle("Family_Common_Fet");
    form.setAction(GWT.getHostPageBaseURL() + "FileUploadGreeting"); 
    form.setWidget(vPanel);

    fileUpload.setName("uploader"); 
    vPanel.add(fileUpload);
    vPanel.setSpacing(20);
    Label maxUpload = new Label();
    maxUpload.setText("Text input file header: Datasheet, Vendor Code");
    vPanel.add(maxUpload);


    final Button submit = new Button("Upload and Run");
    vPanel.add(submit);
    submit.addClickHandler(new ClickHandler() {

        public void onClick(ClickEvent event)
        {
            String filename = fileUpload.getFilename();
            if(!filename.endsWith(".txt"))
            {
                System.out.println(filename);
                Window.alert("only *.txt files accepted");
                return;
            }
            else if(filename.length() == 0)
            {
                Window.alert("Please Select Text File");
                return;
            }
            else
            {
// loading dialog image
                popup.add(new Image("loading_animation1.gif"));
                popup.setGlassEnabled(true); // Enable the glass panel
                popup.center(); // Center the popup and make it visible

                submit.setEnabled(false);
                submit.setFocus(true);
                form.submit();
            }

        }
    });

    // Add an event handler to the form.
    form.addSubmitHandler(new FormPanel.SubmitHandler() {
        public void onSubmit(SubmitEvent event)
        {
            // This event is fired just before the form is submitted. We can take
            // this opportunity to perform validation.

        }
    });
    form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
        public void onSubmitComplete(SubmitCompleteEvent event)
        {

//trying to stop the loading dialodg
            popup.setGlassEnabled(false);

            submit.setEnabled(true);

            form.reset();
        }
    });

    DecoratorPanel decPanel = new DecoratorPanel();
    decPanel.setWidget(form);

    RootPanel.get("uploadContainer").add(decPanel);

}

servlet 代码

public class UploadFileHandler extends HttpServlet
{
private static final long serialVersionUID = 1L;

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

    System.out.println("Inside doPost");

    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload fileUpload = new ServletFileUpload(factory);
    // sizeMax - The maximum allowed size, in bytes. The default value of -1 indicates, that there is no limit.
    // 1048576 bytes = 1024 Kilobytes = 1 x 10 Megabyte
    fileUpload.setSizeMax(10485760);
    System.out.println(request.getRemoteAddr());

    if(!ServletFileUpload.isMultipartContent(request))
    {
        try
        {

            throw new FileUploadException("error multipart request not found");
        }catch(FileUploadException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try
    {

        List<FileItem> items = fileUpload.parseRequest(request);

        if(items == null)
        {
            response.getWriter().write("File not correctly uploaded");
            return;
        }

        Iterator<FileItem> iter = items.iterator();

        String absofilepath = null;
        String fileName = null;
        String filepath = "temp//fileOutput_" + System.currentTimeMillis() + ".txt";
        while(iter.hasNext())
        {
            FileItem item = (FileItem) iter.next();

            ////////////////////////////////////////////////
            // http://commons.apache.org/fileupload/using.html
            ////////////////////////////////////////////////

            // if (item.isFormField()) {
            fileName = item.getName();
            System.out.println("fileName is : " + fileName);
            String typeMime = item.getContentType();
            System.out.println("typeMime is : " + typeMime);
            int sizeInBytes = (int) item.getSize();
            System.out.println("Size in bytes is : " + sizeInBytes);
            // byte[] file = item.get();

            absofilepath = getServletContext().getRealPath(filepath);
            item.write(new File(absofilepath));
            // }

        }

        String request_ip = getClientIpAddr(request);
        System.out.println("Request IP:" + request_ip);

        String tempoutFile = "output//" + fileName + System.currentTimeMillis() + ".txt";
        String absooutFile = getServletContext().getRealPath(tempoutFile);
        System.out.println("ouput file : " + absooutFile);
//************ some other operations in code*******///


}catch(Exception e){
e.printStackTrace();
PrintWriter out = response.getWriter();
response.setHeader("Content-Type", "text/html");
out.println("an Error has occuredin Exporter.bat" + e);
out.flush();
out.close();
}


        // ****************************Downlaod **********************************//
downloadFile(request, response, absooutFile);

 /*when i sing hashed code below it's return error in console and didn't stop the loading dialog image */
//            PrintWriter out = response.getWriter(); 
//            response.setHeader("Content-Type", "text/html"); 
//            out.println("Check output File");
//            System.out.println("Upload Ok");
//             out.flush(); 
//             out.close();


    }catch(SizeLimitExceededException e)
    {
        System.out.println("File size exceeds the limit : 10 MB!!");
        PrintWriter out = response.getWriter();
        response.setHeader("Content-Type", "text/html");
        out.println("Maximum file size should not exceed 10MB!!");
        out.flush();
        out.close();
    }catch(Exception e)
    {
        e.printStackTrace();
        PrintWriter out = response.getWriter();
        response.setHeader("Content-Type", "text/html");
        out.println("an Error has occured");
        out.flush();
        out.close();
    }

}

public static String getClientIpAddr(HttpServletRequest request)
{
    String ip = request.getHeader("X-Forwarded-For");
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
    {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
    {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
    {
        ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
    {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
    {
        ip = request.getRemoteAddr();
    }
    return ip;
}

private void downloadFile(HttpServletRequest req, HttpServletResponse resp, String filePath)
{
    try
    {
        File f = new File(filePath);
        int length = 0;
        ServletOutputStream op = resp.getOutputStream();
        ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(filePath);

        resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        resp.setContentLength((int) f.length());
        resp.setHeader("Content-Disposition", "attachment; filename=Fam_Com_Fet.txt");

        DataInputStream in = new DataInputStream(new FileInputStream(f));
        byte[] bbuf = new byte[in.available()];

        while((in != null) && ((length = in.read(bbuf)) != -1))
        {
            op.write(bbuf, 0, length);
        }

        in.close();
        op.flush();
        op.close();

        // f.delete();


    }catch(IOException ioe)
    {
        ioe.printStackTrace();
    }
}

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

谢谢

【问题讨论】:

    标签: java servlets gwt download


    【解决方案1】:

    SubmitCompleteHandler 只保证在服务器发回 HTML 时被调用,(参见 javadoc)它不适用于任意文件下载。

    【讨论】:

      【解决方案2】:

      感谢 Thomas Broyer 先生说,我将使用正确的代码来说明它。

      一开始,当我在服务器端的 servlet 中使用以下代码时,响应会返回到客户端,因此客户端不会再次执行任何操作,因为它已经请求返回(丢失了请求)。

          // ****************************Downlaod **********************************//
                   downloadFile(request, response, absooutFile);
      

      所以通过使用技术的正确方法允许从客户端触发下载文件操作以保持(请求,响应)激活,以便它能够完成我的操作代码

      所以客户端代码会是这样的

      public class MainGUI extends VerticalPanel implements ClickHandler,     SubmitCompleteHandler
      {
      private FormPanel form = new FormPanel();
      private HTML descriptionLbl = new HTML("Please browse a text <B>[*.txt]</B>     file with header : Datasheet , Vendor code ");
      private HorizontalPanel hPanel = new HorizontalPanel();
      private FileUpload fileUploader = new FileUpload();
      private Button validateBtn = new Button("Import and download");
      private Label errorLbl = new Label("Error message will be here");
      private Image img = new Image("download.png");
      private MyDialog loadingDialog;
      
      
      private LoadingDialog ldialog;
      public MainGUI()
      {
          setSpacing(5);
          hPanel.setSpacing(5);
          errorLbl.setStyleName("error");
      
          form.setMethod(FormPanel.METHOD_POST);
          form.setEncoding(FormPanel.ENCODING_MULTIPART);
          form.setTitle("Fam_Com_Fet");
          form.addSubmitCompleteHandler(this);
      
          validateBtn.addClickHandler(this);
      
          fileUploader.setName("uploader");
      
          hPanel.add(fileUploader);
          add(img);
          setSpacing(20);
          add(hPanel);
          add(validateBtn);
          add(errorLbl);
          add(descriptionLbl);
          form.add(this);
      }
      
      @Override
      public void onClick(ClickEvent event)
      {
      
          exportcommonfeature();
      
      
      
      
      }
      
      private void exportcommonfeature()
      {
          errorLbl.setText("");
          String fileName = fileUploader.getFilename();
          if(fileName == null || fileName.isEmpty())
          {
              errorLbl.setText("No File Specified");
              return;
          }
          if(!fileName.endsWith(".txt"))
          {
              errorLbl.setText("only *.txt files accepted");
              return;
          }
      
      
      
          ldialog = new LoadingDialog();
      
      
          // send the input to the server.
      
          form.setAction(GWT.getHostPageBaseURL() + "UploadFileHandler");
          form.submit();
      }
      
      @Override
      public void onSubmitComplete(SubmitCompleteEvent event)
      {
          form.reset();
      
          if("Error".equalsIgnoreCase(getPlainTextResult(event)))
          {
              errorLbl.setText("Error occured while exporting");
          }else
          {
      

      /********************* 下载请求将在此处触发 ******************* **/

              form.setAction(GWT.getHostPageBaseURL() + "UploadFileHandler?command=download&filepath="+getPlainTextResult(event));
              form.submit();
          }
      

      UploadFileHandler: 正在为我的 servlet 名称映射 URL

      download : UploadFileHandler servlet 中用于下载文件的方法

          ldialog.hide();
      
      
      }
      
      private String getPlainTextResult(SubmitCompleteEvent event)
      {
          HTML html = new HTML(event.getResults());
          System.out.println("MainGUI File Path: " + html.getText());
          return html.getText();
      
      }
      
      public FormPanel getFormPanel()
      {
          return this.form;
      }
      
      }
      

      和 servlet 代码

      public class UploadFileHandler extends HttpServlet
      {
      private static final long serialVersionUID = 1L;
      
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
      {
      
          String filePath = request.getParameter("filepath");
          String commandName = request.getParameter("command");
      
          if("download".equalsIgnoreCase(commandName))
          {
              downloadFile(request, response, filePath);
          }
          else
              generateResultFile(request, response);
      
      }
      
      
      public void generateResultFile(HttpServletRequest request, HttpServletResponse response){
          System.out.println("Inside doPost");
      
          // Create a factory for disk-based file items
          FileItemFactory factory = new DiskFileItemFactory();
          // Create a new file upload handler
          ServletFileUpload fileUpload = new ServletFileUpload(factory);
          // sizeMax - The maximum allowed size, in bytes. The default value of -1 indicates, that there is no limit.
          // 1048576 bytes = 1024 Kilobytes = 1 x 10 Megabyte
          fileUpload.setSizeMax(10485760);
          System.out.println(request.getRemoteAddr());
      
          if(!ServletFileUpload.isMultipartContent(request))
          {
              try
              {
      
                  throw new FileUploadException("error multipart request not found");
              }catch(FileUploadException e)
              {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
      
          try
          {
      
              List<FileItem> items = fileUpload.parseRequest(request);
      
              if(items == null)
              {
                  response.getWriter().write("File not correctly uploaded");
                  return;
              }
      
              Iterator<FileItem> iter = items.iterator();
      
              String absofilepath = null;
              String fileName = null;
              String filepath = "temp//usrinpute_" + System.currentTimeMillis() + ".txt";
              while(iter.hasNext())
              {
                  FileItem item = (FileItem) iter.next();
      
                  ////////////////////////////////////////////////
                  // http://commons.apache.org/fileupload/using.html
                  ////////////////////////////////////////////////
      
                  // if (item.isFormField()) {
                  fileName = item.getName();
                  System.out.println("fileName is : " + fileName);
                  String typeMime = item.getContentType();
                  System.out.println("typeMime is : " + typeMime);
                  int sizeInBytes = (int) item.getSize();
                  System.out.println("Size in bytes is : " + sizeInBytes);
                  // byte[] file = item.get();
      
                  absofilepath = getServletContext().getRealPath(filepath);
                  item.write(new File(absofilepath));
                  // }
      
              }
      
              String request_ip = getClientIpAddr(request);
              System.out.println("Request IP:" + request_ip);
      
              String tempoutFile = "output//" + fileName + System.currentTimeMillis() + ".txt";
              String absooutFile = getServletContext().getRealPath(tempoutFile);
              System.out.println("ouput file : " + absooutFile);
              // **************************************************************************************//
      
      
      
       response.getWriter().write(absooutFile);
      
              // ****************************End Loader**********************************//
      //downloadFile(request, response, absooutFile);
      
      
      
      
      
          }catch(SizeLimitExceededException e)
          {
              System.out.println("File size exceeds the limit : 10 MB!!");
              PrintWriter out = null;
              try
              {
                  out = response.getWriter();
              }catch(IOException e1)
              {
                  // TODO Auto-generated catch block
                  e1.printStackTrace();
              }
              response.setHeader("Content-Type", "text/html");
              out.println("Maximum file size should not exceed 10MB!!");
              out.flush();
              out.close();
          }catch(IOException e)
          {
              try
              {
                  response.getWriter().write("Error");
              }catch(IOException ioe)
              {
                  ioe.printStackTrace();
              }
              e.printStackTrace();
          }catch(Exception e)
          {
              try
              {
                  response.getWriter().write("Error");
              }catch(IOException ioe)
              {
                  ioe.printStackTrace();
              }
              e.printStackTrace();
          }
          }
      
      
      
      public static String getClientIpAddr(HttpServletRequest request)
      {
          String ip = request.getHeader("X-Forwarded-For");
          if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
          {
              ip = request.getHeader("Proxy-Client-IP");
          }
          if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
          {
              ip = request.getHeader("WL-Proxy-Client-IP");
          }
          if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
          {
              ip = request.getHeader("HTTP_CLIENT_IP");
          }
          if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
          {
              ip = request.getHeader("HTTP_X_FORWARDED_FOR");
          }
          if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
          {
              ip = request.getRemoteAddr();
          }
          return ip;
      }
      
      private void downloadFile(HttpServletRequest req, HttpServletResponse resp, String filePath)
      {
          try
          {
              File f = new File(filePath);
              int length = 0;
              ServletOutputStream op = resp.getOutputStream();
              ServletContext context = getServletConfig().getServletContext();
              String mimetype = context.getMimeType(filePath);
      
              resp.setContentType((mimetype != null) ? mimetype : "text/plain");
              resp.setContentLength((int) f.length());
              resp.setHeader("Content-Disposition", "attachment; filename=Family_Common_Features.txt");
      
              DataInputStream in = new DataInputStream(new FileInputStream(f));
              byte[] bbuf = new byte[in.available()];
      
              while((in != null) && ((length = in.read(bbuf)) != -1))
              {
                  op.write(bbuf, 0, length);
              }
      
              in.close();
              op.flush();
              op.close();
      
              // f.delete();
      
      
          }catch(IOException ioe)
          {
              ioe.printStackTrace();
          }
      }
      

      }

      关于模块加载类

          public class Firstmodule implements EntryPoint
      {
      private MainGUI famLayout = new MainGUI();
      
      public void onModuleLoad()
      {
      
          loadingGUI();
      
      }
      
      /**
       * The message displayed to the user when the server cannot be reached or returns an error.
       */
      static final String SERVER_ERROR = "An error occurred while " + "attempting to contact the server. Please check your network " + "connection and try again.";
      
      
      private void loadingGUI()
      {
          VerticalPanel Layout = new VerticalPanel();
          Layout.add(famLayout.getFormPanel());
          Layout.setSpacing(30);
          DecoratorPanel decPanel = new DecoratorPanel();
          decPanel.setWidget(Layout);
          decPanel.setWidth("60%");
          decPanel.setHeight("90%");
          RootPanel.get("uploadContainer").add(decPanel);
      }
      }
      

      将继续加载用于测试响应的对话框类

          public class LoadingDialog extends PopupPanel
      {
      
      public LoadingDialog(){
      
          setGlassEnabled(true);
          setWidget(new Image("loading_animation1.gif"));
          center();
      }
      
      }
      

      这里也是 servlet 映射

          <servlet>
         <servlet-name>UploadFileHandler</servlet-name>
         <servlet-class>edu.file.upload.com.server.UploadFileHandler</servlet-class>
         </servlet>
      
         <servlet-mapping>
         <servlet-name>UploadFileHandler</servlet-name>
         <url-pattern>/FileUploadGreeting</url-pattern>
         </servlet-mapping>
      

      编辑@21-12-2016 只需您可以在服务器端和 onSuccess 下载文件 使用这个表单面板

             FormPanel form = new FormPanel();
               form.setMethod(FormPanel.METHOD_POST);
                                  form.setAction(GWT.getHostPageBaseURL() +    "ServletMappedName?command=download&filePath=" + filePath);
                                  RootPanel.get().add(form);
                                  form.submit();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多