RESTful生成二进制文件 [英] RESTful produces binary file

查看:160
本文介绍了RESTful生成二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用CXF和Spring创建RESTful Web服务的新手。

I'm new using CXF and Spring to make RESTful webservices.

这是我的问题:我想创建一个生成任何类型文件的服务(可以是图像,文档,txt甚至pdf),也可以是XML。到目前为止,我得到了这个代码:

This is my problem: I want to create a service that produces "any" kind of file(can be image,document,txt or even pdf), and also a XML. So far I got this code:

@Path("/download/")
@GET
@Produces({"application/*"})
public CustomXML getFile() throws Exception; 

我不确切知道从哪里开始所以请耐心等待。

I don't know exactly where to begin so please be patient.

编辑:

Bryant Luk的完整代码(谢谢!)

Complete code of Bryant Luk(thanks!)

@Path("/download/")
@GET
public javax.ws.rs.core.Response getFile() throws Exception {
    if (/* want the pdf file */) {
        File file = new File("...");
        return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
            .header("content-disposition", "attachment; filename =" + file.getName())
            .build(); 
    }

    /* default to xml file */
    return Response.ok(new FileInputStream("custom.xml")).type("application/xml").build();
}


推荐答案

如果它将返回任何文件,您可能希望使您的方法更通用并返回一个javax.ws.rs.core.Response,您可以通过编程方式设置Content-Type标头:

If it will return any file, you might want to make your method more "generic" and return a javax.ws.rs.core.Response which you can set the Content-Type header programmatically:

@Path("/download/")
@GET
public javax.ws.rs.core.Response getFile() throws Exception {
    if (/* want the pdf file */) {
        return Response.ok(new File(/*...*/)).type("application/pdf").build(); 
    }

    /* default to xml file */
    return Response.ok(new FileInputStream("custom.xml")).type("application/xml").build();
}

这篇关于RESTful生成二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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