2021-01-03 12:15:16 +08:00
|
|
|
|
package cn.iocoder.dashboard.util.servlet;
|
|
|
|
|
|
|
2021-01-14 21:20:32 +08:00
|
|
|
|
import cn.hutool.core.io.IoUtil;
|
2021-01-03 12:15:16 +08:00
|
|
|
|
import cn.hutool.extra.servlet.ServletUtil;
|
|
|
|
|
|
import com.alibaba.fastjson.JSON;
|
|
|
|
|
|
import org.springframework.http.MediaType;
|
|
|
|
|
|
|
|
|
|
|
|
import javax.servlet.http.HttpServletResponse;
|
2021-01-14 21:20:32 +08:00
|
|
|
|
import java.io.IOException;
|
|
|
|
|
|
import java.net.URLEncoder;
|
2021-01-03 12:15:16 +08:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 客户端工具类
|
|
|
|
|
|
*
|
|
|
|
|
|
* @author 芋道源码
|
|
|
|
|
|
*/
|
|
|
|
|
|
public class ServletUtils {
|
|
|
|
|
|
|
2021-01-14 21:20:32 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 返回 JSON 字符串
|
|
|
|
|
|
*
|
|
|
|
|
|
* @param response 响应
|
|
|
|
|
|
* @param object 对象,会序列化成 JSON 字符串
|
|
|
|
|
|
*/
|
2021-01-03 12:15:16 +08:00
|
|
|
|
@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);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2021-01-14 21:20:32 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 返回附件
|
|
|
|
|
|
*
|
|
|
|
|
|
* @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);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2021-01-03 12:15:16 +08:00
|
|
|
|
}
|