gpt4 book ai didi

java - 将文件从 REST Web 服务发送到客户端的正确方法是什么?

转载 作者:IT老高 更新时间:2023-10-28 11:33:21 33 4
gpt4 key购买 nike

我刚开始开发 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;
}
}

我应该使用什么样的注释?我见过有人推荐使用 @Produces({application/x-octet-stream})@GET,这是正确的方法吗?我发送的文件是特定的,因此客户端不需要浏览这些文件。谁能指导我如何发送文件?我应该使用 base64 对其进行编码以将其作为 JSON 对象发送吗?还是不需要编码就可以将其作为 JSON 对象发送?感谢您提供的任何帮助。

最佳答案

我不建议使用 base64 编码二进制数据并将其包装在 JSON 中。它只会不必要地增加响应的大小并减慢速度。

使用 GET 和 application/octect-stream 使用 javax.ws.rs.core.Response 的工厂方法之一简单地提供您的文件数据(JAX-RS API 的一部分,因此您不会被锁定在 Jersey 中):

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() {
File file = ... // Initialize this to the File path you want to serve.
return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional
.build();
}

如果您没有实际的 File 对象,而是 InputStreamResponse.ok(entity, mediaType)应该也能应付。

关于java - 将文件从 REST Web 服务发送到客户端的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12239868/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com