ResponseFunctions.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package org.ssssssss.magicapi.functions;
  2. import org.springframework.http.HttpHeaders;
  3. import org.springframework.http.MediaType;
  4. import org.springframework.http.ResponseEntity;
  5. import org.ssssssss.magicapi.provider.ResultProvider;
  6. import java.io.UnsupportedEncodingException;
  7. import java.net.URLEncoder;
  8. import java.util.List;
  9. public class ResponseFunctions {
  10. private ResultProvider resultProvider;
  11. public ResponseFunctions(ResultProvider resultProvider) {
  12. this.resultProvider = resultProvider;
  13. }
  14. /**
  15. * 自行构建分页结果
  16. *
  17. * @param total 条数
  18. * @param values 数据内容
  19. */
  20. public Object page(long total, List<Object> values) {
  21. return resultProvider.buildPageResult(total, values);
  22. }
  23. /**
  24. * 自定义json结果
  25. *
  26. * @param value json内容
  27. */
  28. public ResponseEntity json(Object value) {
  29. return ResponseEntity.ok(value);
  30. }
  31. /**
  32. * 展示图片
  33. *
  34. * @param value 图片内容
  35. * @param mime 图片类型,image/png,image/jpeg,image/gif
  36. */
  37. public ResponseEntity image(Object value, String mime) {
  38. return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE, mime).body(value);
  39. }
  40. /**
  41. * 文件下载
  42. *
  43. * @param value 文件内容
  44. * @param filename 文件名
  45. */
  46. public ResponseEntity download(Object value, String filename) throws UnsupportedEncodingException {
  47. return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM)
  48. .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"))
  49. .body(value);
  50. }
  51. }