3
13693261870
2024-07-18 893998916eab354d4002fbcdcb0a242a36a49684
src/main/java/com/se/simu/helper/WebHelper.java
@@ -9,8 +9,7 @@
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.*;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
@@ -189,6 +188,41 @@
    }
    /**
     * 输出字节数组
     */
    public static void writeBytes(byte[] bytes, HttpServletResponse res) throws IOException {
        res.setContentType("application/octet-stream");
        if (null == bytes) {
            res.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        OutputStream os = res.getOutputStream();
        os.write(bytes, 0, bytes.length);
        os.close();
    }
    /**
     * 输出Png文件
     */
    public static void writePng(String filePath, HttpServletResponse res) throws IOException {
        File file = new File(filePath);
        if (!file.exists() || file.isDirectory()) {
            res.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        String fileName = URLEncoder.encode(filePath, "UTF-8").replace("+", "%20");
        res.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
        res.setCharacterEncoding("UTF-8");
        res.setContentType("image/png");
        writeFile(filePath, res);
    }
    /**
     * 获取随机整数
     */
    public static int getRandomInt(int min, int max) {
@@ -227,6 +261,13 @@
        String mime = getMime(ext);
        res.setContentType(mime);
        writeFile(file, res);
    }
    /**
     * 写文件
     */
    private static void writeFile(String file, HttpServletResponse res) throws IOException {
        // 通过response对象,获取到输出流
        ServletOutputStream outputStream = res.getOutputStream();
        // 定义输入流,通过输入流读取文件内容