好久沒有更新博客了,今天來再次總結一下,之前有整理過關於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("\r\n"); 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("\r\n"); 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");
