使用Servlet的GWT FileUpload

时间:2017-05-08 10:35:03

标签: java servlets file-upload gwt

我尝试制作一个非常简单的GWT-Application:用户可以选择一个txt文件并将其上传到服务器。后来我想实现更多功能,但现在我仍然坚持使用FileUpload:

在客户端,我有以下代码:

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

在我的服务器端,我做了以下内容:

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) {

    }
}
}

在web.xml中,我将以下内容添加到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>

我没有收到任何错误消息,但我发现Servlet中的List是空的,因此永远不会执行while循环。请求或提交有问题吗?

1 个答案:

答案 0 :(得分:0)

我对我的代码做了一些更改: 我更改了应用程序布局:我添加了一个TextArea,它显示了上传的txt文件的内容。现在这个非常简单的应用程序将txt文件上传到服务器,然后保存。然后服务器读取txt文件将内容发送到客户端并删除保存的文件。

主要变化:

我给fileupload命名了一个名字:

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

在服务器端的Servlet中,我添加了一个检查,解析后的List是否为空。 我使用path,name和filePath创建文件。然后我用BufferedReader读取文件,然后在响应中写入上下文:

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

我认为问题在于我忘了给fileupload一个名字,因为在我添加了名字之后我测试了代码并且在编写我的文件时突然出现错误。