Blame view

src/main/java/cn/iocoder/dashboard/util/servlet/ServletUtils.java 1.44 KB
fc8eac54   YunaiV   集成 Spring Securit...
1
2
  package cn.iocoder.dashboard.util.servlet;
  
629fa9b4   YunaiV   1. 基于 db 实现文件的存储
3
  import cn.hutool.core.io.IoUtil;
fc8eac54   YunaiV   集成 Spring Securit...
4
5
6
7
  import cn.hutool.extra.servlet.ServletUtil;
  import com.alibaba.fastjson.JSON;
  import org.springframework.http.MediaType;
  
fc8eac54   YunaiV   集成 Spring Securit...
8
  import javax.servlet.http.HttpServletResponse;
629fa9b4   YunaiV   1. 基于 db 实现文件的存储
9
10
  import java.io.IOException;
  import java.net.URLEncoder;
fc8eac54   YunaiV   集成 Spring Securit...
11
12
13
14
15
16
17
18
  
  /**
   * 客户端工具类
   *
   * @author 芋道源码
   */
  public class ServletUtils {
  
629fa9b4   YunaiV   1. 基于 db 实现文件的存储
19
20
21
22
23
24
      /**
       * 返回 JSON 字符串
       *
       * @param response 响应
       * @param object 对象,会序列化成 JSON 字符串
       */
fc8eac54   YunaiV   集成 Spring Securit...
25
26
27
28
29
30
      @SuppressWarnings("deprecation") // 必须使用 APPLICATION_JSON_UTF8_VALUE,否则会乱码
      public static void writeJSON(HttpServletResponse response, Object object) {
          String content = JSON.toJSONString(object);
          ServletUtil.write(response, content, MediaType.APPLICATION_JSON_UTF8_VALUE);
      }
  
629fa9b4   YunaiV   1. 基于 db 实现文件的存储
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
      /**
       * 返回附件
       *
       * @param response 响应
       * @param filename 文件名
       * @param content 附件内容
       * @throws IOException
       */
      public static void writeAttachment(HttpServletResponse response, String filename, byte[] content) throws IOException {
          // 设置 header 和 contentType
          response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
          response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
          // 输出附件
          IoUtil.write(response.getOutputStream(), false, content);
      }
  
fc8eac54   YunaiV   集成 Spring Securit...
47
  }