【发布时间】:2012-08-27 17:15:35
【问题描述】:
我刚刚开始开发 REST 服务,但遇到了一个困难的情况:将文件从我的 REST 服务发送到我的客户端。到目前为止,我已经掌握了如何发送简单数据类型(字符串、整数等)的窍门,但是发送文件是另一回事,因为文件格式太多,我什至不知道应该从哪里开始。我的 REST 服务是在 Java 上创建的,我使用的是 Jersey,我使用 JSON 格式发送所有数据。
我读过关于 base64 编码的文章,有人说这是一种很好的技术,其他人说这不是因为文件大小问题。正确的方法是什么?这是我项目中一个简单资源类的外观:
import java.sql.SQLException;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import com.mx.ipn.escom.testerRest.dao.TemaDao;
import com.mx.ipn.escom.testerRest.modelo.Tema;
@Path("/temas")
public class TemaResource {
@GET
@Produces({MediaType.APPLICATION_JSON})
public List<Tema> getTemas() throws SQLException{
TemaDao temaDao = new TemaDao();
List<Tema> temas=temaDao.getTemas();
temaDao.terminarSesion();
return temas;
}
}
我猜发送文件的代码是这样的:
import java.sql.SQLException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/resourceFiles")
public class FileResource {
@GET
@Produces({application/x-octet-stream})
public File getFiles() throws SQLException{ //I'm not really sure what kind of data type I should return
// Code for encoding the file or just send it in a data stream, I really don't know what should be done here
return file;
}
}
我应该使用什么样的注释?我看到有人推荐@GET 使用@Produces({application/x-octet-stream}),这是正确的方法吗?我发送的文件是特定的,因此客户端不需要浏览这些文件。谁能指导我如何发送文件?我应该使用 base64 对其进行编码以将其作为 JSON 对象发送吗?还是不需要编码就可以将其作为 JSON 对象发送?感谢您提供的任何帮助。
【问题讨论】:
-
您的服务器上是否有实际的
java.io.File(或文件路径),或者数据是否来自其他来源,如数据库、Web 服务、返回InputStream的方法调用?
标签: java json web-services rest jersey