GWT FileUpload与Servlet [英] GWT FileUpload with Servlet

查看:197
本文介绍了GWT FileUpload与Servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试做一个非常简单的GWT应用程序:用户可以选择一个txt文件上传到服务器。后来我想实现更多的功能,但现在我卡在FileUpload上:



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

  public class GwtDemoProject implements EntryPoint {

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

私有FormPanel表单;
私人标签信息;
private FileUpload fileupload;
私人按钮uploadFileBtn;

public void onModuleLoad(){

init();
$ b $ uploadFileBtn.addClickHandler(new ClickHandler(){
@Override
public void onClick(ClickEvent event){
String filename = fileupload.getFilename();
$ b $ 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 $ b $ 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 =新标签(Wähleeine Textdatei aus);

fileupload = new FileUpload();

uploadFileBtn =新建按钮(上传文件);






在我的服务器端,我做了以下操作: p>

  public class FileUploadServlet extends HttpServlet 
{

private static final long serialVersionUID = 1L;
$ b @Override
保护无效doPost(HttpServletRequest请求,HttpServletResponse响应)
抛出ServletException,IOException {
response.setContentType(text / html);

尝试{
DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);


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

迭代器< FileItem> iter = items.iterator(); (iter.hasNext()){
FileItem item = iter.next();

File uploadedFile = new File(C:\\\\\\\\\\\\\\\\\\\\\)
item.write(uploadedFile);



$ catch(Exception exc){




在web.xml中,我将以下内容添加到Servlet中:

 <! -  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循环永远不会执行。请求或提交有问题吗?

解决方案

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



主要更改:

<我给了fileupload一个名字:

  public class GwtFileUploadDemo implements EntryPoint {

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

私有FormPanel表单;
私人标签信息;
private FileUpload fileupload;
私人按钮uploadFileBtn;
private TextArea outputText;

public void onModuleLoad(){

init();
$ b $ uploadFileBtn.addClickHandler(new ClickHandler(){
@Override
public void onClick(ClickEvent event){
String filename = fileupload.getFilename();
$ b $ 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);
}
}
});

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

if (event.getResults()。length()== 0){
Window.alert(出错了,再试一次);
} 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 =新标签(选择一个txt文件);

fileupload = new FileUpload();

//这里我给fileuploader添加了一个名字
fileupload.setName(uploader);

uploadFileBtn = new Button(显示txt文件的内容);

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






在服务器端的Servlet中,如果解析的List是空的。
我用路径,名称和文件路径创建文件。然后我用BufferedReader读取文件,然后在响应中写上下文:

pre $ public $ FileUploadServlet extends HttpServlet
{

private static final long serialVersionUID = 1L;
$ b $ @覆盖$ b $保护无效doPost(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException {

System.out.println(Inside doPost);

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

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

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

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

迭代器< FileItem> iter = items.iterator(); (iter.hasNext()){
FileItem item = iter.next();

while(iter.hasNext
System.out.println(开始写入文件);

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; ((line = bufferedReader.readLine())!= null){
content = content + line +\\\
;


}

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




$ b我认为问题在于我忘了给fileupload的名字,因为我添加了名称后,我测试了代码,突然得到错误,写我的文件。

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.

这篇关于GWT FileUpload与Servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆