Действие формы не остановилось после загрузки файла с сервлетами в GWT?

Я разработал небольшое приложение в 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);

}

код сервлета

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();

            ////////////////////////////////////////////////
            // https://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);
}

Спасибо

См. также:  Как включить разветвленное репо из Git в мой java-проект eclipse?
Понравилась статья? Поделиться с друзьями:
IT Шеф
Комментарии: 2
  1. Nothig

    SubmitCompleteHandler гарантированно вызывается только тогда, когда сервер отправляет обратно HTML (см. javadoc), он не будет работать для загрузки произвольного файла.

  2. Nothig

    Спасибо, мистер Томас Бройер Саид, и я приведу правильный код для иллюстрации того, что я получил.

    в начале, когда я использовал приведенный ниже код в своем сервлете на стороне сервера, ответ возвращается клиенту, поэтому на стороне клиента ничего не будет выполняться снова, поскольку он уже возвращает запрос (потерял запрос).

        // ****************************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: сопоставляет URL-адрес моего имени сервлета

    download : это метод в сервлете UploadFileHandler для загрузки файла.

        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;
    }
    
    }
    

    и код сервлета

    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();
    
                ////////////////////////////////////////////////
                // https://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-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, просто вы можете загрузить свой файл на стороне сервера и в случае успеха использовать эту панель формы.

           FormPanel form = new FormPanel();
             form.setMethod(FormPanel.METHOD_POST);
                                form.setAction(GWT.getHostPageBaseURL() +    "ServletMappedName?command=download&filePath=" + filePath);
                                RootPanel.get().add(form);
                                form.submit();
    
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: