小编典典

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

json

我刚刚开始开发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对象发送?感谢您提供的任何帮助。


阅读 255

收藏
2020-07-27

共1个答案

小编典典

我不建议在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对象,但是InputStream,也Response.ok(entity, mediaType)应该能够处理该对象。

2020-07-27