简体   繁体   English

以JSON响应(Java-Jersey-ReST)返回文件

[英]Returning file/files in JSON response (Java-Jersey-ReST)

I am working on a use case where I am displaying user's messages on a JSP. 我正在研究一个用例,其中在JSP上显示用户的消息。 Details of the flow are: 该流程的详细信息是:

  • All the messages will be shown in a table with icon for attachments 所有邮件将显示在带有附件图标的表格中
  • When the user clicks on attachment, the file should get downloaded. 当用户单击附件时,应下载文件。
  • If there is more than one attachment, user can select the required one to download. 如果附件不止一个,则用户可以选择所需的附件进行下载。
  • The attachments will be stored on the local filesystem and the path for the attachments will be determined by the system. 附件将存储在本地文件系统上,附件的路径将由系统确定。

I have tried to implement by referring to these SO questions: 我试图通过参考这些SO问题来实现:

However, it's not solving my purpose. 但是,这并不能解决我的目的。 I have the following questions: 我有以下问题:

  1. Is it possible to send message data (like subject, message, message id, etc) along with the attachments (Inputstream) in one response? 是否可以在一个响应中将消息数据(例如主题,消息,消息ID等)与附件(Inputstream)一起发送?
  2. If yes, what needs to be the MediaType for @Produces annotation in my resource method? 如果是,我的资源方法中@Produces注释的MediaType应该是什么? Currently my resource is annotated with @Produces(MediaType.APPLICATION_JSON) . 目前,我的资源使用@Produces(MediaType.APPLICATION_JSON)注释。 Will this work? 这样行吗?
  3. How to send the file data in the response? 如何在响应中发送文件数据?

Any pointers appreciated. 任何指针表示赞赏。 TIA. TIA。

  1. You can add custom data to the response Header, so yes you are able to send such message data. 您可以将自定义数据添加到响应头,因此可以发送此类消息数据。 Add the data to the response Header. 将数据添加到响应头。

  2. @Produces(MediaType.APPLICATION_JSON) will not work, unless the clients will accept JSON as a file, what they should and will not do ;) @Produces(MediaType.APPLICATION_JSON)将不起作用,除非客户端将JSON作为文件接受,否则他们应该做什么和不应该做什么;)

    The correct MediaType depends on what kind of file you want to submit. 正确的MediaType取决于您要提交的文件类型。

    You can use the default MediaType / MIME-Type MediaType.APPLICATION_OCTET_STREAM / application/octet-stream ( Is there a “default” MIME type? ) but I think it's better to use the correct and exact MIME-Type for your file. 您可以使用默认的MediaType / MIME类型MediaType.APPLICATION_OCTET_STREAM / application/octet-stream是否存在“默认” MIME类型? ),但我认为最好为文件使用正确的MIME类型。

  3. You will find working examples for sending file data with jersey in Input and Output binary streams using JERSEY? 您将找到使用JERSEY输入和输出二进制流中使用 jersey发送文件数据的工作示例 - so there is no need to answer this again :) -因此无需再次回答:)

Hope this was helpful somehow, have a nice day. 希望这对您有所帮助,祝您有愉快的一天。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM