使用Jersey和RestyGWT下载文件

时间:2013-07-18 09:51:54

标签: gwt jersey

您可以通过列表作为参数

从服务器下载文件

使用 RestyGWT Jersey 1.7?

在服务器端,我有以下网络服务

@POST
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/download")
public Response downloadFiles(@Context HttpServletResponse response, List<FileInfo> files) {
    ZipFile zip = null;

    String uuid = UUID.randomUUID().toString();
    response.setHeader("Content-Disposition", "attachment; filename="
            + uuid + ".zip");
    try {
        zip = new ZipFile(response.getOutputStream());
        File f = new File(ConfigurationLoader.getRealPath("/logo.png"));
        zip.addFile(f, "");
        zip.getOutputStream().flush();
        zip.getOutputStream().close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

当我在浏览器中键入 localhost:8080 / Url / download 时,它可以正常工作,但我如何使用Resty Gwt或Window.open()下载文件?

我想使用 POST 而不是GET,所以我可以传递可序列化对象的列表,例如: 列出文件

我在客户端尝试使用RestyGWT:

@POST
@Produces("application/zip")
@Path("/download")
public void downloadFiles(List<FileInfo> files, MethodCallback<Response> response);

private static final Resource resource = new Resource(
                GWT.getHostPageBaseURL() + "rest/files");

        public static final FileRestService get() {
            if (instance == null) {
                instance = GWT.create(FileRestService.class);
                ((RestServiceProxy) instance).setResource(resource);
            }
            return instance;
        }

但它无法正常工作,我无法找到有关在restygwt中下载文件的示例

1 个答案:

答案 0 :(得分:2)

一般情况下(*)您不能使用ajax下载文件,因此您必须使用Window.open()iframe来要求用户将文件另存为。

在此查询中查看我的回复:Window.open in GWT not open correctly with in a call back function

当然使用iframe你不能使用POST,但你可以编写一个循环来在每次加载最后一个iframe时请求一个不同的文件。系统会多次询问用户下载文件。

您可以使用FormPanel,然后添加一些隐藏参数并将其发布到服务器。 FormPanel在隐藏的iframe中显示响应,因此设置适当的标题(内容类型内容 - 处置),您可以下载文件并要求用户另存为。我会压缩文件集,以便用户可以保存或打开内容,因为更多操作系统具有可视化压缩文件的实用程序。

(*)使用XHR可以下载文件,但是您需要一种方法来处理内容并将其显示给用户。它通常用于文本文件html,txt,xml等。查看html5 api以接收和处理二进制数据。但是,您无法在用户的文件系统中创建文件。