Вопросы

Действие формы не остановилось после загрузки файла с сервлетами в 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);
}

Спасибо

Читать:
Python не в порядке: как подключить другие языки к Python

Похожие записи

RuntimeError: цикл событий закрывается при попытке выполнить запрос https с помощью aiohttp

admin

Почему мой код добавляет элемент в массив при следующем щелчке по React-javascript

admin

Запуск JupyterQ из Anaconda Navigator

admin

Предоставленный параллелизм не разрешает холодный запуск лямбда

admin

VSCode при обнаружении тестов Ошибка: порождение python ENOENT

admin

Vapor 4 PostgreSQL CRUD без HTTP-запросов

admin