jersey实现文件下载

     好久没有更新博客了,今天来再次总结一下,之前有整理过关于jersey实现文件上传功能的相关知识,但是前一阵子在实习过程中写接口又要实现文件下载的功能,由于这些东西基本都是使用jersey提供的注解和接口来实现的,因此,实现起来就是有种套模板的感觉,废话不多说,我们来看看是如何实现的吧。

    第一步,实现resource接口(注意上面的注解声明的返回类型):

 1     @POST
 2     @Path("/export")
 3     @Produces("application/x-msdownload")
 4     public StreamingOutput exportIndicator(@HeaderParam("userId") int userId, EmotionDetailListPageModel emotionDetailListPageModel) {
 5            //调用service实现业务
 6           return CSVUtils.exportData(result); 7     }

   其次,在CSVUtils里是返回的是什么内容呢?一下是该类所做的事情:将调用service得到的结果传入,返回一个实现了StreamingOutput接口的实例,实现该接口中的write方法,将java的对象写入流中,

注意在这里为了使得代码具有更好的扩展性,使用反射来获取对应对象中的数据。

 1  public static StreamingOutput exportData(List<EmotionDetailListModel> list) {
 2  
 3         return new StreamingOutput() {
 4             @Override
 5             public void write(OutputStream output) throws IOException, WebApplicationException {
 6                 Writer writer = null;
 7                 writer = new BufferedWriter(new OutputStreamWriter(output, "GB18030"));//GB18030
 8                 if (list.isEmpty()) {
 9                     throw new RuntimeException("没有要导出的数据");
10                 }
11                 // reflect to get file title
12                 Field[] fAll = list.get(0).getClass().getDeclaredFields();
13                 writer.write(generateTitle(fAll));
14                 writer.write("
");
15 
16                 for (EmotionDetailListModel emotionDetailListModel : list) {
17                     try {
18                         logger.info("write success" + parseModelToCSVStr(emotionDetailListModel));
19                         writer.write(parseModelToCSVStr(emotionDetailListModel));
20                     } catch (IllegalAccessException e) {
21                         throw new RuntimeException("转换错误,错误信息:" + e);
22                     }
23                     writer.write("
");
24                 }
25                 writer.flush();
26             }
27         };
28     }

我们可以看出,前端拿到的就是一个StreamOutput对象,当然,我们也可以将文件的名称和类型通过response传给前端,这样,下载的文件类型和名称都会是指定的名称。

1   httpServletResponse.setHeader("Content-Disposition", "attachment; filename="" + emotionDetailListPageModel.getGameid() + "." + "csv" + """);
2   httpServletResponse.setHeader("Content-Type", "text/csv; charset=utf-8");
原文地址:https://www.cnblogs.com/jy107600/p/7810073.html