package com.bcxin.survey.utils; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.RandomUtil; import com.bcxin.survey.domain.wechat.AccessToken; import com.bcxin.survey.service.obs.OBSUtil; import com.bcxin.survey.service.oss.OSSServiceExecutor; import com.google.common.collect.Lists; import com.google.common.io.Files; import org.apache.commons.lang3.StringUtils; import org.jboss.logging.Logger; import org.springframework.web.multipart.MultipartFile; import sun.misc.BASE64Decoder; import javax.imageio.ImageIO; import javax.net.ssl.HttpsURLConnection; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author 罗鹏 */ public class FileUtils { /** * 文件加时间戳的连接符 */ private final static String TI = "_t_"; /** * 默认文件上传路径 */ private final static String DEFAULT_UPLOAD_DIR = "upload"; private static Logger logger = Logger.getLogger(FileUtils.class); public final static String DOT = "."; //点 /** * * @param base64Str * @param directoryName * @param customFileName (a.jpg) * @return */ public static Map ossFileUpload(String base64Str,String directoryName,String customFileName){ Map map = new HashMap(); String fileType = StringUtils.substringAfterLast(customFileName, Const.DOT).toLowerCase(); // a.jpg String fileName = customFileName; if(directoryName.endsWith(Const.SLASH)) { directoryName = directoryName.substring(0, directoryName.length() - 1); } String ossKey = directoryName + Const.SLASH + fileName; OSSServiceExecutor ossExecutor = new OSSServiceExecutor(Const.IMAGE_FORM.contains(fileType)); try { if ( !ossExecutor.isExitsDirectory(directoryName) ) { ossExecutor.createDirectory(directoryName); } new Thread(()->{ //异步上传处理 try { ossExecutor.put(ossKey, BaseToInputStream(base64Str), true); } catch(Exception e) { e.printStackTrace(); logger.error(e.getMessage(), e); } }).start(); String url = ossExecutor.getServer() + ossKey; map.put("url", url); map.put("key", ossKey); } catch ( Exception e) { e.printStackTrace(); logger.error(e.getMessage(), e); } return map; } /** * * @param base64Str * @param dir * @param fileName (a.jpg) * @return */ public static String huaweiOBSFileUpload_base64(String base64Str,String dir,String fileName){ if(StringUtils.isNotEmpty(dir)){ dir = dir.startsWith("/")?dir:"/"+dir; dir = dir.endsWith("/")?dir.substring(0,dir.length()-1):dir; } /* 生成目录 */ String directoryName = DEFAULT_UPLOAD_DIR+ dir + "/" + DateUtil.getCurrentDate() + "/"; String ossKey = DEFAULT_UPLOAD_DIR+ dir + "/" + DateUtil.getCurrentDate() + "/" + fileName; OBSUtil obsUtil = new OBSUtil(); /* 利用jdk7的特性,执行完后自动关闭流对象 */ try (InputStream inputStream = BaseToInputStream(base64Str)) { return obsUtil.put(directoryName, ossKey, inputStream); } catch (Exception e) { e.printStackTrace(); logger.error("huaweiOBSFileUpload_base64:"+e.getMessage(), e); } return ""; } /** * 华为OBS文件上传存储(同步) * * @return */ public static String huaweiOBSFileUpload(MultipartFile xFile, String dir) { /* 获得文件后缀名 jpg*/ String fileType = Files.getFileExtension(xFile.getOriginalFilename()); /* 生成随机文件名 12345*/ String randomNumber = System.currentTimeMillis() + RandomUtil.randomNumbers(6); /* 组装成随机文件名称 12345.jpg */ String fileName = randomNumber + DOT + fileType; if(StringUtils.isNotEmpty(dir)){ dir = dir.startsWith("/")?dir:"/"+dir; dir = dir.endsWith("/")?dir.substring(0,dir.length()-1):dir; } /* 生成目录 */ String directoryName = DEFAULT_UPLOAD_DIR+ dir + "/" + DateUtil.getCurrentDate() + "/"; String ossKey = DEFAULT_UPLOAD_DIR+ dir + "/" + DateUtil.getCurrentDate() + "/" + fileName; OBSUtil obsUtil = new OBSUtil(); /* 利用jdk7的特性,执行完后自动关闭流对象 */ try (InputStream inputStream = xFile.getInputStream()) { return obsUtil.put(directoryName, ossKey, inputStream); } catch (Exception e) { e.printStackTrace(); logger.error("huaweiOBSFileUpload:"+e.getMessage(), e); } return ""; } public static String huaweiOBSFileUpload(InputStream inputStream, String dir, String fileType) { /* 生成随机文件名 12345*/ String randomNumber = System.currentTimeMillis() + RandomUtil.randomNumbers(6); /* 组装成随机文件名称 12345.jpg */ String fileName = randomNumber + DOT + fileType; if(StringUtils.isNotEmpty(dir)){ dir = dir.startsWith("/")?dir:"/"+dir; dir = dir.endsWith("/")?dir.substring(0,dir.length()-1):dir; } /* 生成目录 */ String directoryName = DEFAULT_UPLOAD_DIR+ dir + "/" + DateUtil.getCurrentDate() + "/"; String ossKey = DEFAULT_UPLOAD_DIR+ dir + "/" + DateUtil.getCurrentDate() + "/" + fileName; OBSUtil obsUtil = new OBSUtil(); /* 利用jdk7的特性,执行完后自动关闭流对象 */ try { return obsUtil.put(directoryName, ossKey, inputStream); } catch (Exception e) { e.printStackTrace(); logger.error("huaweiOBSFileUpload:"+e.getMessage(), e); } return ""; } /** * 华为OBS文件上传存储(同步) * * @return */ public static String huaweiOBSFileUpload(File file, String fileType, String dir) { /* 生成随机文件名 12345*/ String randomNumber = System.currentTimeMillis() + RandomUtil.randomNumbers(6); /* 组装成随机文件名称 12345.jpg */ String fileName = randomNumber + DOT + fileType; if(StringUtils.isNotEmpty(dir)){ dir = dir.startsWith("/")?dir:"/"+dir; dir = dir.endsWith("/")?dir.substring(0,dir.length()-1):dir; } /* 生成目录 */ String directoryName = DEFAULT_UPLOAD_DIR+ dir + "/" + DateUtil.getCurrentDate() + "/"; String ossKey = DEFAULT_UPLOAD_DIR+ dir + "/" + DateUtil.getCurrentDate() + "/" + fileName; OBSUtil obsUtil = new OBSUtil(); /* 利用jdk7的特性,执行完后自动关闭流对象 */ try (InputStream inputStream = FileUtil.getInputStream(file)) { return obsUtil.put(directoryName, ossKey, inputStream); } catch (Exception e) { e.printStackTrace(); logger.error("huaweiOBSFileUpload(envi:"+ConfigUtil.envi()+",fileType:"+fileType+",obsUtil:"+(obsUtil==null?"null":"not null")+"):"+e.getMessage(), e); } return ""; } /** * 华为OBS文件上传存储(本地文件上传到华为公共云) * * @return */ public static String huaweiLocalFileUpload(File file, String date, String dir) { if(StringUtils.isNotEmpty(dir)){ dir = dir.startsWith("/")?dir:"/"+dir; dir = dir.endsWith("/")?dir.substring(0,dir.length()-1):dir; } /* 生成目录 */ String directoryName = DEFAULT_UPLOAD_DIR+ dir + "/" + date + "/"; String ossKey = DEFAULT_UPLOAD_DIR+ dir + "/" + date + "/" + file.getName(); OBSUtil obsUtil = new OBSUtil(); /* 利用jdk7的特性,执行完后自动关闭流对象 */ try (InputStream inputStream = FileUtil.getInputStream(file)) { return obsUtil.put(directoryName, ossKey, inputStream); } catch (Exception e) { e.printStackTrace(); logger.error("huaweiLocalFileUpload:"+e.getMessage(), e); } return ""; } public static void downloadAllFile(String path, HttpServletResponse response, String upload_path) { try { if (path.contains("..")) { return; } File file = new File(upload_path + path); String fileName = file.getName(); if (file != null) { ServletOutputStream out = response.getOutputStream(); response.addHeader("Content-Disposition", "attachment;filename=" + fileName); response.setContentLength((int)file.length());//servlet-api3没有setContentLengthLong InputStream is = new FileInputStream(file); int read = 0; byte[] buffer = new byte[8192]; while ((read = is.read(buffer)) != -1) { out.write(buffer, 0, read); } is.close(); out.flush(); out.close(); } } catch (Exception e){ e.printStackTrace(); } } /** * base64转inputStream * @param base64string * @return */ private static InputStream BaseToInputStream(String base64string){ ByteArrayInputStream stream = null; try { BASE64Decoder decoder = new BASE64Decoder(); byte[] bytes1 = decoder.decodeBuffer(base64string); stream = new ByteArrayInputStream(bytes1); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); logger.error(e.getMessage(), e); } return stream; } // 下载url文件 public static String download(String urlString, String filename, String savePath){ FileOutputStream fos = null; InputStream inputStream = null; try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置超时间为10秒 conn.setConnectTimeout(10 * 1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 inputStream = conn.getInputStream(); //获取自己数组 byte[] getData = readInputStream(inputStream); //文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdirs(); } File file = new File(saveDir + File.separator + filename); fos = new FileOutputStream(file); fos.write(getData); String filePath = saveDir + "/" + filename; return filePath; } catch (Exception e){ e.printStackTrace(); logger.error(e.getMessage(), e); return ""; } finally { try { if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException e){ e.printStackTrace(); logger.error(e.getMessage(), e); } } } // 下载url文件 public static String downloadForHttps(String urlString, String filename, String savePath){ FileOutputStream fos = null; InputStream inputStream = null; try { URL url = new URL(urlString); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); //设置超时间为10秒 conn.setConnectTimeout(10 * 1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); conn.setHostnameVerifier(new CustomizedHostnameVerifier()); //得到输入流 inputStream = conn.getInputStream(); //获取自己数组 byte[] getData = readInputStream(inputStream); //文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdirs(); } File file = new File(saveDir + File.separator + filename); fos = new FileOutputStream(file); fos.write(getData); String filePath = saveDir + "/" + filename; return filePath; } catch (Exception e){ e.printStackTrace(); logger.error(e.getMessage(), e); return ""; } finally { try { if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException e){ e.printStackTrace(); logger.error(e.getMessage(), e); } } } private static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } /** * 根据系统默认存储路径的方式,获取其中的文件路径 * example : 参数 local_1497333054610||/getResource.do?path=2017-06-13/1497333054610.jpg||4.jpg&&local_1497333054610||/getResource.do?path=2017-06-13/1497333054611.jpg||4.jpg * result : 2017-06-13/1497333054610.jpg 2017-06-13/1497333054611.jpg * @param localFilePath * @return */ public static List filterMultiFilePath(String localFilePath){ List list = Lists.newArrayList(); if (StringUtil.isEmpty(localFilePath)) { return list; } String[] filePaths = StringUtils.split(localFilePath, "&&"); for(String filePath : filePaths){ if (filePath.indexOf("||")>-1) { String[] explain = StringUtils.split(filePath, "||"); if (explain.length < 3) { continue; } String localUrl = explain[1]; if (localUrl.indexOf("path=") == -1) { continue; } localUrl = localUrl.substring(localUrl.indexOf("path=")+5,localUrl.length()); list.add(localUrl); } if (filePath.startsWith("http")) { list.add(filePath); } } return list; } /** * 根据系统的地址,下载文件到新的路径 * @param urlStr * @param fileName * @param savePath * @return * @throws IOException */ public static List downLoadFromUrl(String urlStr, String fileName, String savePath){ if (StringUtil.isEmpty(urlStr)){ return Lists.newArrayList(); } if (StringUtil.isNotEmpty(fileName)) { fileName = fileName.replace("/",""); } List pathList = Lists.newArrayList(); String[] imageValues = urlStr.split("&&"); int count = 1; for (String imageValue : imageValues) { String disposeFileName = fileName; String[] splitStr = StringUtil.split(imageValue,"||"); //再从一张图片url里面切分到url String imagePath = ""; if (splitStr.length >= 3) { imagePath = splitStr[1]; } else { imagePath = urlStr; } if ( count > 1 ) { if ( disposeFileName.contains(".") ){ disposeFileName = disposeFileName.substring(0,disposeFileName.lastIndexOf(".")) + count ; } else { disposeFileName = disposeFileName + count; } } if (imagePath.startsWith("http")) { String filePath = ""; disposeFileName = disposeFileName + imagePath.substring(imagePath.lastIndexOf("."),imagePath.length()); filePath = download(imagePath, disposeFileName, savePath); pathList.add(filePath); } else if (imagePath.indexOf("path=") > 0) { String web_url = GlobalResources.WEB_URL; if (StringUtil.isNotEmpty(web_url)) { if (web_url.endsWith("/") && imagePath.endsWith("/") ){ web_url = web_url.substring(0,web_url.length()-1); } } imagePath = web_url + imagePath; disposeFileName = disposeFileName + imagePath.substring(imagePath.lastIndexOf("."),imagePath.length()); //本地获取 // uploadPath + imagePath.split("path=")[1]; String filePath = download(imagePath, disposeFileName, savePath); pathList.add(filePath); } count++; } return pathList; } /** * 处理文件夹路径 * @param paths * @return */ public static String appendFolderPath(String[] paths){ StringBuilder sb = new StringBuilder(); for (String path:paths) { if (sb.length()==0) { sb.append(path); } else { /*if (sb.toString().endsWith(File.separator)) { sb.append(path).append(File.separator); } else { sb.append(File.separator).append(path).append(File.separator); }*/ if (sb.toString().endsWith("/")) { sb.append(path).append("/"); } else { sb.append("/").append(path).append("/"); } } } mkDir(sb.toString());//创建文件夹 return sb.toString(); } /** * 创建文件夹 * @param dir */ public static void mkDir(String dir){ File fileDir = new File(dir); if(!fileDir.exists()) { fileDir.mkdirs(); } } /** * 为文件名增加时间戳 * @return */ public static String packTimestamp(String fileName){ if (StringUtil.isEmpty(fileName)) { return Const.BLANK_CHAR; } if (fileName.contains(Const.DOT)) { return Files.getNameWithoutExtension(fileName) + TI + DateUtil.getTimestamp() + Files.getFileExtension(fileName); } else { return fileName + TI + DateUtil.getTimestamp() ; } } /** * 根据系统默认存储路径的方式,获取其中的文件路径 * example : 参数 /getResource.do?path=2017-06-13/1497333054610.jpg * result : 2017-06-13/1497333054610.jpg * @param localFilePath * @return */ public static String filterSingleFilePath(String localFilePath){ if (StringUtil.isEmpty(localFilePath)) { return Const.BLANK_CHAR; } if ( localFilePath.contains("path=")) { return localFilePath.substring(localFilePath.indexOf("path=")+5,localFilePath.length()); } return localFilePath; } /** * 远程图片降质 * @author ZXF * @create 2024/06/28 0028 17:42 * @version * @注意事项 */ public static String reduceQualityImg(String url){ long no = System.currentTimeMillis(); String fileName = no + ".jpg";//随机生成新文件名 String fileNameOth = no + "oth.jpg";//随机生成新文件名 String path = ConfigUtil.envi() + "/temp/" + DateUtil.getCurrentDate(DateUtil.FORMAT2)+"/"; String savePath = ConfigUtil.material() + path; // 返回文件路径地址 String filePath=FileUtils.downloadForHttps(url, fileName, savePath); String newPath = savePath+fileNameOth; try { if(StringUtil.isNotEmpty(filePath)){ scale(filePath, newPath, 100001, false); String[] folderPath = new String[]{ConfigUtil.material(), cn.hutool.core.date.DateUtil.today()}; String dir = FileUtils.appendFolderPath(folderPath); return huaweiOBSFileUpload(new File(newPath),"jpg",dir); } } catch (Exception e) { e.printStackTrace(); } finally { try { //删除临时文件 (new File(filePath)).delete(); (new File(newPath)).delete(); } catch (Exception e) { logger.error("===========> reduceQualityImg.临时文件删除失败.error:"+e.getMessage()+",filePath:"+filePath+",newPath:"+newPath); } } return ""; } /** * 缩放图像(按比例缩放) *

* scale 缩放比例 * * @param srcImageFile 源图像文件地址 * @param result 缩放后的图像地址 * @param flag 缩放选择:true 放大; false 缩小; * @param length 文件大小 * @Author 张建华 */ public static void scale(String srcImageFile, String result, float length, boolean flag) { float scale = 1; if (length > 20000) { scale = 1.5f; } else if (length > 50000) { scale = 2.0f; } else if (length > 100000) { scale = 3.0f; } try { // 读入文件 BufferedImage src = ImageIO.read(new File(srcImageFile)); // 得到源图宽 int width = src.getWidth(); // 得到源图长 int height = src.getHeight(); // 放大 if (flag) { width = (int) (width * scale); height = (int) (height * scale); } else { // 缩小 width = (int) (width / scale); height = (int) (height / scale); } Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT); BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); // 绘制缩小后的图 g.drawImage(image, 0, 0, null); g.dispose(); // 输出到文件流 ImageIO.write(tag, "JPEG", new File(result)); } catch (IOException e) { e.printStackTrace(); } } }