【问题标题】:Use content-disposition attachment in RemoteServiceServlet在 RemoteServiceServlet 中使用内容处置附件
【发布时间】:2012-02-04 22:20:50
【问题描述】:

我有一个应用程序成功地从用户接收输入字符串,在服务器端处理它,并在网页上显示结果。我将它实现为 RemoteServiceServlet,因为这样我可以轻松处理所有网站小工具。

尽管如此,我还是决定,而不是在网页上显示结果,而是使用“内容处置附件”的可能性,以便用户可以将处理后的字符串下载到 txt 文件中。

有没有办法在不将整个应用程序从 RemoteServiceServlet 更改为 HttpServlet 的情况下做到这一点?

在我的代码下方。谢谢一百万。

ProjectServiceImpl.java

public class ProjectServiceImpl extends RemoteServiceServlet implements ProjectService 
{
    public String project(String input) throws IllegalArgumentException 
    {
        String output = processString(input);
        // Below something I tried to do, but it does not work at all
        try {
            HttpServletResponse resp = getThreadLocalResponse();
        resp.reset();
        resp.setContentType("application/octet-stream");
        resp.setContentLength(10);
        resp.setHeader("Content-disposition", "attachment; filename=\"test.txt\"");
        ServletOutputStream op = resp.getOutputStream();
        op.write(convertToByteArray(output),0,10);
        op.flush();
        op.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return output;
    }
}

ProjectService.java

public interface ProjectService extends RemoteService {
    String project(String name) throws IllegalArgumentException;
}

ProjectServiceAsync.java

public interface ProjectServiceAsync {
    void project(String input, AsyncCallback<String> callback)
            throws IllegalArgumentException;
}

MyProject.java:客户端

[...]
projectService.project(originalString, new AsyncCallback<String>() {
    [...]
    public void onSuccess(final String result) 
    {
        [...] // Or perhaps should I create here in client-side the txt file with "result"
    }
});

【问题讨论】:

    标签: java gwt httprequest content-disposition


    【解决方案1】:

    与其更改为另一个 servlet,不如考虑使用其中的一个 - RPC 用作传输的 XmlHttpRequest 不能用于下载文件,但对于您对服务器的几乎所有请求仍然非常方便。 XHR 仅适用于从 javascript 到服务器的通信,不能用于下载(或其他事情,例如打开带有内容的新窗口)。

    考虑创建另一个 servlet,并让 RPC 调用返回一个字符串、另一个 servlet 的 url(可能加上一些其他参数来指示应该下载的内容)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      • 2011-03-16
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      相关资源
      最近更新 更多