简体   繁体   中英

GWT FileUpload with Servlet

I try to make a very simple GWT-Application: The User can choose a txt file an upload it to the Server. Later I want to implement more functionality but for now I'm stuck on the FileUpload:

On the client Side I have the following Code working:

public class GwtDemoProject implements EntryPoint {

private static final String UPLOAD_ACTION_URL = GWT.getModuleBaseURL() + "upload";

private FormPanel form;
private Label info;
private FileUpload fileupload;
private Button uploadFileBtn;

public void onModuleLoad() {

    init();

    uploadFileBtn.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            String filename = fileupload.getFilename();

            if(filename.length() == 0) {
                Window.alert("File Upload failed");
            } else if(filename.endsWith(".txt")) {

                form.submit();

            } else {
                Window.alert("File is not a txt-file");
            }
        }
    });     

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

            if(event.getResults().length() == 0) {

            } else {
                Window.alert(event.getResults());
            }
        }
    });


    VerticalPanel vp = new VerticalPanel();
    vp.add(info);
    vp.add(fileupload);
    vp.add(new HTML("<br>"));
    vp.add(uploadFileBtn);

    form.add(vp);
    RootPanel rp = RootPanel.get();
    rp.add(form);
}

private void init() {
    form = new FormPanel();
    form.setAction(UPLOAD_ACTION_URL);
    form.setEncoding(FormPanel.ENCODING_MULTIPART);
    form.setMethod(FormPanel.METHOD_POST);

    info = new Label("Wähle eine Textdatei aus");

    fileupload = new FileUpload();

    uploadFileBtn = new Button("Upload File");
}
}

On my server side I made the following:

public class FileUploadServlet extends HttpServlet
{

private static final long serialVersionUID = 1L;

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");       

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();            

        ServletFileUpload upload = new ServletFileUpload(factory);


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

        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            File uploadedFile = new File("C:\\samplePath\\"+item.getName()+".txt");
            item.write(uploadedFile);

        }


    } catch (Exception exc) {

    }
}
}

In the web.xml I added the following to the Servlets:

 <!-- Servlets -->
    <servlet>
        <servlet-name>uploadServlet</servlet-name>
        <servlet-class>de.gwt.demo.server.FileUploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>uploadServlet</servlet-name>
        <url-pattern>/gwtdemoproject/upload</url-pattern>
    </servlet-mapping>

I get no error message but I found out that the List in the Servlet is empty so the while loop is never executed. Is something wrong with the request or the submit?

I made some changes to my code: I changed the application layout: I added a TextArea which displays the content of the uploaded txt file. Now this very simple Application take a txt file uploads it to the server, where it gets saved. Then the Server reads the txt file sends the content to the client and deletes the saved file.

Major changes:

I gave the fileupload a name:

public class GwtFileUploadDemo implements EntryPoint {

private static final String UPLOAD_ACTION_URL = GWT.getModuleBaseURL() + "upload";

private FormPanel form;
private Label info;
private FileUpload fileupload;
private Button uploadFileBtn;
private TextArea outputText;

public void onModuleLoad() {

    init();

    uploadFileBtn.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            String filename = fileupload.getFilename();

            if(filename.length() == 0) {
                Window.alert("File Upload failed");
            } else if(filename.endsWith(".txt")) {

                form.submit();          

            } else {
                Window.alert("File is not a txt file");
            }
        }
    });


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

            if(event.getResults().length() == 0) {
                Window.alert("Something went wrong - Try again");
            } else {
                outputText.setText(event.getResults());                 
            }
        }
    });


    VerticalPanel vp = new VerticalPanel();
    vp.add(info);
    vp.add(fileupload);
    vp.add(new HTML("<br>"));
    vp.add(uploadFileBtn);
    vp.add(outputText);

    form.add(vp);
    RootPanel rp = RootPanel.get();
    rp.add(form);
}

private void init() {
    form = new FormPanel();
    form.setAction(UPLOAD_ACTION_URL);
    form.setEncoding(FormPanel.ENCODING_MULTIPART);
    form.setMethod(FormPanel.METHOD_POST);

    info = new Label("Choose a txt file");

    fileupload = new FileUpload();

    //Here I added a name to the fileuploader
    fileupload.setName("uploader");

    uploadFileBtn = new Button("Show content of txt File");

    outputText = new TextArea();
    outputText.setEnabled(false);
}
}

In the Servlet on the Server side I added a check if the parsed List is empty. I create the file with the path, name, and filePath. Then I read the file with a BufferedReader and I write the context in the response:

public class FileUploadServlet extends HttpServlet
{

private static final long serialVersionUID = 1L;

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {      

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

    try {
        if (!ServletFileUpload.isMultipartContent(request)) {                                 
            throw new FileUploadException("error multipart request not found");              
        }       

        DiskFileItemFactory factory = new DiskFileItemFactory();            

        ServletFileUpload upload = new ServletFileUpload(factory);

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

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

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

        while (iter.hasNext()) {
            FileItem item = iter.next();
            System.out.println("Start writing File");

            String uploadPath = ".";
            String fileName = new File(item.getName()).getName();
            String filePath = uploadPath + File.separator + fileName;

            System.out.println("File-Pfad:" + filePath);        

            File uploadedFile = new File(filePath);
            item.write(uploadedFile);               

            String content = "";  

            FileReader fileReader = new FileReader(filePath);

            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line = null;

            while((line = bufferedReader.readLine()) != null) {
                content = content + line + "\n";
            }   

            bufferedReader.close();  

            PrintWriter out = response.getWriter();
            response.setHeader("Content-Type", "text/html");
            out.println(content);
            out.flush();
            out.close(); 

            uploadedFile.delete();

            System.out.println("Finished reading File");
        }

    } catch (Exception exc) {
        exc.printStackTrace();
        PrintWriter out = response.getWriter();
        response.setHeader("Content-Type", "text/html");
        out.println("Error");
        out.flush();
        out.close();
    }
    System.out.println("FileUploadServlet doPost end");
}
}

I think the problem was that I forgot to give the fileupload a name, because after I added the name I tested the Code and suddenly got Errors with writing my file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM