From 893998916eab354d4002fbcdcb0a242a36a49684 Mon Sep 17 00:00:00 2001 From: 13693261870 <252740454@qq.com> Date: 星期四, 18 七月 2024 11:28:14 +0800 Subject: [PATCH] 3 --- src/main/java/com/se/simu/helper/WebHelper.java | 45 +++++++++++++++++++++++++++++++++++++++++++-- 1 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/se/simu/helper/WebHelper.java b/src/main/java/com/se/simu/helper/WebHelper.java index adc8d82..66985bd 100644 --- a/src/main/java/com/se/simu/helper/WebHelper.java +++ b/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(); // 瀹氫箟杈撳叆娴侊紝閫氳繃杈撳叆娴佽鍙栨枃浠跺唴瀹� -- Gitblit v1.9.3