使用POI技术往Excel中写入图片并以附件的形式发送给对方

    xiaoxiao2022-07-12  149

    使用POI技术往Excel中写入图片

    Service层代码fastDFS工具类ExcelUtil工具类

    Service层代码

    @Service public class UserChangeService { @Autowired private FastDFSClient fastDFSClient; @Autowired private TransactionTemplate template; @Autowired private GkshopUsersDirectoriesDOMapper directoriesDOMapper; /** * 手动发送邮件到移动 * * @param listId 主建ID * @return * @author huaiyan */ public int sendEmailToMobile(List<Integer> listId) { try { if (StringUtil.isEmpty(listId)) { return -1; } int result = template.execute(new TransactionCallback<Integer>() { @Override public Integer doInTransaction(TransactionStatus status) { //根据主键批量查询对象 List<GkshopUserExchangeDO> list = queryExchangDoByID(listId); if (StringUtil.isEmpty(list)) { return -2; } //将查询出的信息作为一个map,以附件的形式发送给对方 List<Map<String, Object>> listMap = new ArrayList<>(); int size = list.size(); for (int i = 0; i < size; i++) { Map<String, Object> map = new HashMap<>(16); GkshopUserExchangeDO userExchangeDO = list.get(i); if (StringUtil.isEmpty(userExchangeDO)) { //对象为空,则跳过此对象 continue; } //得到手机号 String phoneNumber = userExchangeDO.getPhoneNumber(); //得到最新上传身份证的ID Integer directoriesIdNew = userExchangeDO.getDirectoriesIdNew(); if (StringUtil.isEmpty(directoriesIdNew)) { //实名人ID为空,则跳过此对象 continue; } //根据主键查询对象 GkshopUsersDirectoriesDO gkshopUsersDirectoriesDO = directoriesDOMapper.selectByPrimaryKey(directoriesIdNew); if (StringUtil.isEmpty(gkshopUsersDirectoriesDO)) { //实名人为空,则跳过此对象 continue; } //实名人姓名 String realName = gkshopUsersDirectoriesDO.getRealName(); //身份号 String identificationCard = gkshopUsersDirectoriesDO.getIdentificationCard(); //得到正面证件路径 String identificationPositive = gkshopUsersDirectoriesDO.getIdentificationPositive(); //得到反面证件路径 String identificationReverse = gkshopUsersDirectoriesDO.getIdentificationReverse(); byte[] positive = null; byte[] reverse = null; try { positive = fastDFSClient.download(identificationPositive); reverse = fastDFSClient.download(identificationReverse); } catch (Exception e) { logger.error("UserChangeService.doInTransaction error:" + e); logger.info("UserChangeService.doInTransaction info={}", "fastDFS下载身份证发送异常!"); return -3; } map.put("phoneNumber", phoneNumber); map.put("realName", realName); map.put("identificationCard", identificationCard); map.put("positive", positive); map.put("reverse", reverse); listMap.add(map); } InputStream iputStream = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String[] columnName = {"变更手机号", "实名人", "身份证", "正面照", "反面照"}; String[] key= {"phoneNumber", "realName", "identificationCard", "positive", "reverse"}; try { ExcelUtil.createBookAndInsertImage(listMap, key, columnName).write(outputStream); outputStream.flush(); byte[] outPut = outputStream.toByteArray(); iputStream = new ByteArrayInputStream(outPut, 0, outPut.length); } catch (Exception e) { logger.error("UserChangeService.doInTransaction error:" + e); logger.info("UserChangeService.doInTransaction info={}", "数据转化成输入流异常!"); return -4; } //获得抄送人 String messageTypeCc = SettingHelper.getSettingVal(SystemSettingEnums.SEND_EMAIL_EXCEL_TO, String.class); //获得收件人 String messageTypeTo = SettingHelper.getSettingVal(SystemSettingEnums.SEND_EMAIL_EXCEL_CC, String.class); //附件名字及后缀 String fuJian = "【极客科技】变更实名人申请汇总.xls"; //邮件主题 String subject = "【极客科技】手机卡号变更实名人申请汇总"; //邮件正文内容 String emailText = "这是一份有关于【极客科技】名下的手机卡号申请更换实名人的汇总邮件,详情查看附件!"; boolean flag = WordToEmailUtil.sendEmailToSomeOne(iputStream, subject, emailText, messageTypeTo, messageTypeCc, fuJian); if (flag) { //说明邮件发送成功了! //修改这些数据的字段为已发送邮件,进度为已受理 GkshopUserExchangeQuery exchangeQuery = new GkshopUserExchangeQuery(); GkshopUserExchangeQuery.Criteria criteria = exchangeQuery.createCriteria(); criteria.andIdIn(listId); GkshopUserExchangeDO gkshopUserExchangeDO = new GkshopUserExchangeDO(); //从已审核(2)-->已受理(3) gkshopUserExchangeDO.setStatus(UserExChangStatusEnums.ALREADYACCEPT.getValue()); //最新发送邮件时间 gkshopUserExchangeDO.setUpdateTime(new Date()); gkshopUserExchangeDO.setSendStatus(1); gkshopUserExchangeDO.setSendTime(new Date()); exchangeDOMapper.updateByExampleSelective(gkshopUserExchangeDO, exchangeQuery); return 1; } else { return -5; } } }); return result; } catch (Exception e) { logger.error("UserChangeService.sendEmailToMobile error:" + e); return -6; } } }

    fastDFS工具类

    package com.geenk.market.common.util.fastdfs.client; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.csource.common.MyException; import org.csource.common.NameValuePair; import org.csource.fastdfs.FileInfo; import org.csource.fastdfs.ProtoCommon; import org.csource.fastdfs.StorageClient1; import org.csource.fastdfs.TrackerServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * FastDFS Java API. 文件上传下载主类. * * @author 120841 * @date 2018年12月18日16:29:29 */ @Component public class FastDFSClient { /*** * */ public static final String KEY = "GeenkShop123!@#"; /** * 路径分隔符 */ public static final String SEPARATOR = "/"; /** * Point */ public static final String POINT = "."; /** * ContentType */ public static final Map<String, String> EXT_MAPS = new HashMap<>(); /** * org.slf4j.Logger */ private static Logger logger = LoggerFactory.getLogger(FastDFSClient.class); /** * 文件名称Key */ private static final String FILENAME = "filename"; /** * 文件最大的大小 */ private int maxFileSize = 100 * 1000 * 1000; private FastDFSClient fastDFSClient = null; @PostConstruct private void initFastDFSClient(){ if (fastDFSClient == null) { fastDFSClient = new FastDFSClient(); } } public FastDFSClient() { initExt(); } private void initExt() { // image EXT_MAPS.put("png", "image/png"); EXT_MAPS.put("gif", "image/gif"); EXT_MAPS.put("bmp", "image/bmp"); EXT_MAPS.put("ico", "image/x-ico"); EXT_MAPS.put("jpeg", "image/jpeg"); EXT_MAPS.put("jpg", "image/jpeg"); // 压缩文件 EXT_MAPS.put("zip", "application/zip"); EXT_MAPS.put("rar", "application/x-rar"); // doc EXT_MAPS.put("pdf", "application/pdf"); EXT_MAPS.put("ppt", "application/vnd.ms-powerpoint"); EXT_MAPS.put("xls", "application/vnd.ms-excel"); EXT_MAPS.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); EXT_MAPS.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"); EXT_MAPS.put("doc", "application/msword"); EXT_MAPS.put("doc", "application/wps-office.doc"); EXT_MAPS.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); EXT_MAPS.put("txt", "text/plain"); // 音频 EXT_MAPS.put("mp4", "video/mp4"); EXT_MAPS.put("flv", "video/x-flv"); } /** * MultipartFile 上传文件 * * @param file MultipartFile * @return 返回上传成功后的文件路径 */ public String uploadFileWithMultipart(MultipartFile file) throws FastDFSException { return upload(file, null); } /** * MultipartFile 上传文件 * * @param file MultipartFile * @param descriptions 文件描述 * @return 返回上传成功后的文件路径 */ public String uploadFileWithMultipart(MultipartFile file, Map<String, String> descriptions) throws FastDFSException { return upload(file, descriptions); } /** * 根据指定的路径上传文件 * * @param filepath 文件路径 * @return 返回上传成功后的文件路径 */ public String uploadFileWithFilepath(String filepath) throws FastDFSException { return upload(filepath, null); } /** * 根据指定的路径上传文件 * * @param filepath 文件路径 * @param descriptions 文件描述 * @return 返回上传成功后的文件路径 */ public String uploadFileWithFilepath(String filepath, Map<String, String> descriptions) throws FastDFSException { return upload(filepath, descriptions); } /** * 上传base64文件 * * @param base64 文件base64 * @return 返回上传成功后的文件路径 */ public String uploadFileWithBase64(String base64) throws FastDFSException { return upload(base64, null, null); } /** * 上传base64文件 * * @param base64 文件base64 * @param filename 文件名 * @return 返回上传成功后的文件路径 */ public String uploadFileWithBase64(String base64, String filename) throws FastDFSException { return upload(base64, filename, null); } /** * 上传base64文件 * * @param base64 文件base64 * @param filename 文件名 * @param descriptions 文件描述信息 * @return 返回上传成功后的文件路径 */ public String uploadFileWithBase64(String base64, String filename, Map<String, String> descriptions) throws FastDFSException { return upload(base64, filename, descriptions); } /** * 使用 MultipartFile 上传 * * @param file MultipartFile * @param descriptions 文件描述信息 * @return 文件路径 * @throws FastDFSException file为空则抛出异常 */ public String upload(MultipartFile file, Map<String, String> descriptions) throws FastDFSException { if (file == null || file.isEmpty()) { throw new FastDFSException(ErrorCode.FILE_ISNULL.CODE, ErrorCode.FILE_ISNULL.MESSAGE); } String path = null; try { path = upload(file.getInputStream(), file.getOriginalFilename(), descriptions); } catch (IOException e) { logger.error("FastDFSClient.upload error:",e); throw new FastDFSException(ErrorCode.FILE_ISNULL.CODE, ErrorCode.FILE_ISNULL.MESSAGE); } return path; } /** * 根据指定的路径上传 * * @param filepath 文件路径 * @param descriptions 文件描述 * @return 文件路径 * @throws FastDFSException 文件路径为空则抛出异常 */ public String upload(String filepath, Map<String, String> descriptions) throws FastDFSException { if (StringUtils.isBlank(filepath)) { throw new FastDFSException(ErrorCode.FILE_PATH_ISNULL.CODE, ErrorCode.FILE_PATH_ISNULL.MESSAGE); } File file = new File(filepath); String path = null; try { InputStream is = new FileInputStream(file); // 获取文件名 filepath = toLocal(filepath); String filename = filepath.substring(filepath.lastIndexOf("/") + 1); path = upload(is, filename, descriptions); } catch (FileNotFoundException e) { logger.error("FastDFSClient.upload error:",e); throw new FastDFSException(ErrorCode.FILE_NOT_EXIST.CODE, ErrorCode.FILE_NOT_EXIST.MESSAGE); } return path; } /** * 上传base64文件 * * @param base64 * @param filename 文件名 * @param descriptions 文件描述信息 * @return 文件路径 * @throws FastDFSException base64为空则抛出异常 */ public String upload(String base64, String filename, Map<String, String> descriptions) throws FastDFSException { if (StringUtils.isBlank(base64)) { throw new FastDFSException(ErrorCode.FILE_ISNULL.CODE, ErrorCode.FILE_ISNULL.MESSAGE); } return upload(new ByteArrayInputStream(Base64.decodeBase64(base64)), filename, descriptions); } /** * 上传通用方法 * * @param is 文件输入流 * @param filename 文件名 * @param descriptions 文件描述信息 * @return 组名+文件路径,如:group1/M00/00/00/wKgz6lnduTeAMdrcAAEoRmXZPp870.jpeg * @throws FastDFSException */ public String upload(InputStream is, String filename, Map<String, String> descriptions) throws FastDFSException { if (is == null) { throw new FastDFSException(ErrorCode.FILE_ISNULL.CODE, ErrorCode.FILE_ISNULL.MESSAGE); } try { if (is.available() > maxFileSize) { throw new FastDFSException(ErrorCode.FILE_OUT_SIZE.CODE, ErrorCode.FILE_OUT_SIZE.MESSAGE); } } catch (IOException e) { logger.error("FastDFSClient.upload error:",e); } filename = toLocal(filename); // 返回路径 String path = null; // 文件描述 NameValuePair[] nvps = null; List<NameValuePair> nvpsList = new ArrayList<>(); // 文件名后缀 String suffix = getFilenameSuffix(filename); // 文件名 if (StringUtils.isNotBlank(filename)) { nvpsList.add(new NameValuePair(FILENAME, filename)); } // 描述信息 if (descriptions != null && descriptions.size() > 0) { for (Map.Entry<String, String> entry : descriptions.entrySet()) { nvpsList.add(new NameValuePair(entry.getKey(), entry.getValue())); } // descriptions.forEach((key, value) -> { nvpsList.add(new NameValuePair(key, value)); }); } if (nvpsList.size() > 0) { nvps = new NameValuePair[nvpsList.size()]; nvpsList.toArray(nvps); } TrackerServer trackerServer = TrackerServerPool.borrowObject(); StorageClient1 storageClient = new StorageClient1(trackerServer, null); try { // 读取流 byte[] fileBuff = new byte[is.available()]; is.read(fileBuff, 0, fileBuff.length); // 上传 path = storageClient.upload_file1(fileBuff, suffix, nvps); if (StringUtils.isBlank(path)) { throw new FastDFSException(ErrorCode.FILE_UPLOAD_FAILED.CODE, ErrorCode.FILE_UPLOAD_FAILED.MESSAGE); } if (logger.isDebugEnabled()) { logger.debug("upload file success, return path is {}", path); } } catch (IOException e) { logger.error("FastDFSClient.upload error:",e); throw new FastDFSException(ErrorCode.FILE_UPLOAD_FAILED.CODE, ErrorCode.FILE_UPLOAD_FAILED.MESSAGE); } catch (MyException e) { logger.error("FastDFSClient.upload error:",e); throw new FastDFSException(ErrorCode.FILE_UPLOAD_FAILED.CODE, ErrorCode.FILE_UPLOAD_FAILED.MESSAGE); } finally { // 关闭流 if (is != null) { try { is.close(); } catch (IOException e) { logger.error("FastDFSClient.upload error:",e); } } } // 返还对象 TrackerServerPool.returnObject(trackerServer); return path; } /** * 以附件形式下载文件 * * @param filepath 文件路径 * @param response */ public void downloadFile(String filepath, HttpServletResponse response) throws FastDFSException { download(filepath, null, null, response); } /** * 下载文件 输出文件 * * @param filepath 文件路径 * @param os 输出流 */ public void downloadFile(String filepath, OutputStream os) throws FastDFSException { download(filepath, null, os, null); } /** * 以附件形式下载文件 可以指定文件名称. * * @param filepath 文件路径 * @param filename 文件名称 * @param response HttpServletResponse */ public void downloadFile(String filepath, String filename, HttpServletResponse response) throws FastDFSException { download(filepath, filename, null, response); } /** * 下载文件 * * @param filepath 文件路径 * @param filename 文件名称 * @param os 输出流 * @param response HttpServletResponse */ public void download(String filepath, String filename, OutputStream os, HttpServletResponse response) throws FastDFSException { if (StringUtils.isBlank(filepath)) { throw new FastDFSException(ErrorCode.FILE_PATH_ISNULL.CODE, ErrorCode.FILE_PATH_ISNULL.MESSAGE); } filepath = toLocal(filepath); // 文件名 if (StringUtils.isBlank(filename)) { filename = getOriginalFilename(filepath); } String contentType = EXT_MAPS.get(getFilenameSuffix(filename)); if (logger.isDebugEnabled()) { logger.debug("download file, filepath = {}, filename = {}", filepath, filename); } TrackerServer trackerServer = TrackerServerPool.borrowObject(); StorageClient1 storageClient = new StorageClient1(trackerServer, null); InputStream is = null; try { // 下载 byte[] fileByte = storageClient.download_file1(filepath); if (fileByte == null) { throw new FastDFSException(ErrorCode.FILE_NOT_EXIST.CODE, ErrorCode.FILE_NOT_EXIST.MESSAGE); } if (response != null) { os = response.getOutputStream(); // 设置响应头 if (StringUtils.isNotBlank(contentType)) { // 文件编码 处理文件名中的 '+'、' ' 特殊字符 String encoderName = URLEncoder.encode(filename, "UTF-8").replace("+", " ").replace("+", "+"); response.setHeader("Content-Disposition", "attachment;filename=\"" + encoderName + "\""); response.setContentType(contentType + ";charset=UTF-8"); response.setHeader("Accept-Ranges", "bytes"); } } is = new ByteArrayInputStream(fileByte); byte[] buffer = new byte[1024 * 5]; int len = 0; while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } os.flush(); } catch (IOException e) { logger.error("FastDFSClient.download error:",e); } catch (MyException e) { logger.error("FastDFSClient.download error:",e); throw new FastDFSException(ErrorCode.FILE_DOWNLOAD_FAILED.CODE, ErrorCode.FILE_DOWNLOAD_FAILED.MESSAGE); } finally { // 关闭流 try { if (is != null) { is.close(); } if (os != null) { os.close(); } } catch (IOException e) { e.printStackTrace(); } } // 返还对象 TrackerServerPool.returnObject(trackerServer); } /** * 下载文件 * * @param filepath 文件路径 * @return 返回文件字节 * @throws FastDFSException */ public byte[] download(String filepath) throws FastDFSException { if (StringUtils.isBlank(filepath)) { throw new FastDFSException(ErrorCode.FILE_PATH_ISNULL.CODE, ErrorCode.FILE_PATH_ISNULL.MESSAGE); } TrackerServer trackerServer = TrackerServerPool.borrowObject(); StorageClient1 storageClient = new StorageClient1(trackerServer, null); InputStream is = null; byte[] fileByte = null; try { fileByte = storageClient.download_file1(filepath); if (fileByte == null) { throw new FastDFSException(ErrorCode.FILE_NOT_EXIST.CODE, ErrorCode.FILE_NOT_EXIST.MESSAGE); } } catch (IOException e) { logger.error("FastDFSClient.download error:",e); } catch (MyException e) { logger.error("FastDFSClient.download error:",e); throw new FastDFSException(ErrorCode.FILE_DOWNLOAD_FAILED.CODE, ErrorCode.FILE_DOWNLOAD_FAILED.MESSAGE); } // 返还对象 TrackerServerPool.returnObject(trackerServer); return fileByte; } /** * 删除文件 * * @param filepath 文件路径 * @return 删除成功返回 0, 失败返回其它 */ public int deleteFile(String filepath) throws FastDFSException { if (StringUtils.isBlank(filepath)) { throw new FastDFSException(ErrorCode.FILE_PATH_ISNULL.CODE, ErrorCode.FILE_PATH_ISNULL.MESSAGE); } TrackerServer trackerServer = TrackerServerPool.borrowObject(); StorageClient1 storageClient = new StorageClient1(trackerServer, null); int success = 0; try { success = storageClient.delete_file1(filepath); if (success != 0) { throw new FastDFSException(ErrorCode.FILE_DELETE_FAILED.CODE, ErrorCode.FILE_DELETE_FAILED.MESSAGE); } } catch (IOException e) { logger.error("FastDFSClient.deleteFile error:",e); } catch (MyException e) { logger.error("FastDFSClient.deleteFile error:",e); throw new FastDFSException(ErrorCode.FILE_DELETE_FAILED.CODE, ErrorCode.FILE_DELETE_FAILED.MESSAGE); } // 返还对象 TrackerServerPool.returnObject(trackerServer); return success; } /** * 获取文件信息 * * @param filepath 文件路径 * @return 文件信息 * * <pre> * {<br> * "SourceIpAddr": 源IP <br> * "FileSize": 文件大小 <br> * "CreateTime": 创建时间 <br> * "CRC32": 签名 <br> * } <br> * </pre> */ public Map<String, Object> getFileInfo(String filepath) throws FastDFSException { TrackerServer trackerServer = TrackerServerPool.borrowObject(); StorageClient1 storageClient = new StorageClient1(trackerServer, null); FileInfo fileInfo = null; try { fileInfo = storageClient.get_file_info1(filepath); } catch (IOException e) { logger.error("FastDFSClient.getFileInfo error:",e); } catch (MyException e) { logger.error("FastDFSClient.getFileInfo error:",e); } // 返还对象 TrackerServerPool.returnObject(trackerServer); Map<String, Object> infoMap = new HashMap<>(4); infoMap.put("SourceIpAddr", fileInfo.getSourceIpAddr()); infoMap.put("FileSize", fileInfo.getFileSize()); infoMap.put("CreateTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(fileInfo.getCreateTimestamp())); infoMap.put("CRC32", fileInfo.getCrc32()); return infoMap; } /** * 获取文件描述信息 * * @param filepath 文件路径 * @return 文件描述信息 */ public Map<String, Object> getFileDescriptions(String filepath) throws FastDFSException { TrackerServer trackerServer = TrackerServerPool.borrowObject(); StorageClient1 storageClient = new StorageClient1(trackerServer, null); NameValuePair[] nvps = null; try { nvps = storageClient.get_metadata1(filepath); } catch (IOException e) { logger.error("FastDFSClient.getFileDescriptions error:",e); } catch (MyException e) { logger.error("FastDFSClient.getFileDescriptions error:",e); } // 返还对象 TrackerServerPool.returnObject(trackerServer); Map<String, Object> infoMap = null; if (nvps != null && nvps.length > 0) { infoMap = new HashMap<>(nvps.length); for (NameValuePair nvp : nvps) { infoMap.put(nvp.getName(), nvp.getValue()); } } return infoMap; } /** * 获取源文件的文件名称 * * @param filepath 文件路径 * @return 文件名称 */ public String getOriginalFilename(String filepath) throws FastDFSException { Map<String, Object> descriptions = getFileDescriptions(filepath); if (descriptions.get(FILENAME) != null) { return (String) descriptions.get(FILENAME); } return null; } /** * 获取文件名称的后缀 * * @param filename 文件名 或 文件路径 * @return 文件后缀 */ public static String getFilenameSuffix(String filename) { String suffix = null; String originalFilename = filename; if (StringUtils.isNotBlank(filename)) { if (filename.contains(SEPARATOR)) { filename = filename.substring(filename.lastIndexOf(SEPARATOR) + 1); } if (filename.contains(POINT)) { suffix = filename.substring(filename.lastIndexOf(POINT) + 1); } else { if (logger.isErrorEnabled()) { logger.error("filename error without suffix : {}", originalFilename); } } } return suffix; } /** * 转换路径中的 '\' 为 '/' <br> * 并把文件后缀转为小写 * * @param path 路径 * @return */ public static String toLocal(String path) { if (StringUtils.isNotBlank(path)) { path = path.replaceAll("\\\\", SEPARATOR); if (path.contains(POINT)) { String pre = path.substring(0, path.lastIndexOf(POINT) + 1); String suffix = path.substring(path.lastIndexOf(POINT) + 1).toLowerCase(); path = pre + suffix; } } return path; } /** * 获取FastDFS文件的名称,如:M00/00/00/wKgzgFnkTPyAIAUGAAEoRmXZPp876.jpeg * * @param fileId 包含组名和文件名,如:group1/M00/00/00/wKgzgFnkTPyAIAUGAAEoRmXZPp876.jpeg * @return FastDFS 返回的文件名:M00/00/00/wKgzgFnkTPyAIAUGAAEoRmXZPp876.jpeg */ public static String getFilename(String fileId) { String[] results = new String[2]; StorageClient1.split_file_id(fileId, results); return results[1]; } /** * 获取访问服务器的token,拼接到地址后面 * * @param filepath 文件路径 group1/M00/00/00/wKgzgFnkTPyAIAUGAAEoRmXZPp876.jpeg * @param httpSecretKey 秘钥 * @return 返回token,如: token=078d370098b03e9020b82c829c205e1f&ts=1508141521 */ public static String getToken(String filepath, String httpSecretKey) { // unix seconds // int ts = (int) Instant.now().getEpochSecond(); int ts = (int) (System.currentTimeMillis() / 1000); // token String token = "null"; try { token = ProtoCommon.getToken(getFilename(filepath), ts, httpSecretKey); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (MyException e) { e.printStackTrace(); } StringBuilder sb = new StringBuilder(); sb.append("token=").append(token); sb.append("&ts=").append(ts); return sb.toString(); } /** * @return the max file size */ public int getMaxFileSize() { return maxFileSize; } /** * Set max file size, default 100M * * @param maxFileSize the max file size */ public void setMaxFileSize(int maxFileSize) { this.maxFileSize = maxFileSize; } /** * 测试 */ public static void main(String[] args) throws Exception { } }

    ExcelUtil工具类

    public class ExcelUtil{ /** * 用于在Excel中插入数据和图片,但是图片只能放两张,而且只能放在最后两列(图片必须是byte[]形式的) * @param list List<Map<String, Object>>数据的封装,keys和columnName一一对应 * @param keys map的key String keys[] = {"phoneNumber", "realName", "identificationCard", "positive", "reverse"}; * @param columnName 列名 String columnName[] = {"变更手机号", "实名人", "身份证", "正面照", "反面照"}; * @return * @author huaiyan */ public static Workbook createBookAndInsertImage(List<Map<String, Object>> list, String[] keys, String columnName[]) { //创建Excel文件(Workbook) HSSFWorkbook workbook = new HSSFWorkbook(); try { // 创建第一个sheet(页) HSSFSheet sheet = workbook.createSheet(); // 创建第一行 Row row = sheet.createRow((short) 0); // 创建两种单元格格式 CellStyle styleOne = workbook.createCellStyle(); // 创建第一种字体 Font fontOne = workbook.createFont(); // 设置第一种单元格的样式(用于列名) styleOne.setFont(fontOne); styleOne.setBorderLeft(CellStyle.BORDER_THIN); styleOne.setBorderRight(CellStyle.BORDER_THIN); styleOne.setBorderTop(CellStyle.BORDER_THIN); styleOne.setBorderBottom(CellStyle.BORDER_THIN); styleOne.setAlignment(CellStyle.ALIGN_CENTER); // 创建第一种字体样式(用于列名) fontOne.setFontHeightInPoints((short) 10); //设置黑体 fontOne.setColor(IndexedColors.BLACK.getIndex()); fontOne.setBoldweight(Font.BOLDWEIGHT_BOLD); // 创建第二种字体 Font fontTwo = workbook.createFont(); CellStyle styleTwo = workbook.createCellStyle(); // 设置第二种单元格的样式(用于值) styleTwo.setFont(fontTwo); styleTwo.setBorderLeft(CellStyle.BORDER_THIN); styleTwo.setBorderRight(CellStyle.BORDER_THIN); styleTwo.setBorderTop(CellStyle.BORDER_THIN); styleTwo.setBorderBottom(CellStyle.BORDER_THIN); //设置垂直居中 styleTwo.setAlignment(CellStyle.ALIGN_CENTER); styleTwo.setVerticalAlignment((short) 1); // 创建第二种字体样式(用于值) fontTwo.setFontHeightInPoints((short) 10); fontTwo.setColor(IndexedColors.BLACK.getIndex()); //设置第一行的标题样式宽度 int length = keys.length; for (int i = 0; i < length; i++) { sheet.setColumnWidth((short) i, (short) (35.7 * 250)); } //设置列名 for (int i = 0; i < columnName.length; i++) { Cell cell = row.createCell(i); cell.setCellValue(columnName[i]); cell.setCellStyle(styleOne); } int size = list.size(); //设置每行每列的值 for (short i = 0; i < size; i++) { // Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的 // 在页sheet上创建第二行, Row rowTwo = sheet.createRow((short) i + 1); //从第二行开始每一行设置高度 rowTwo.setHeight((short) (100*20)); //这个就是等效于上面的写法 // rowTwo.setHeightInPoints(100); // 在row行上创建一个方格 for (short j = 0; j < length; j++) { if (j>=length-2){ HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFClientAnchor anchorP = new HSSFClientAnchor(0, 0, 0, 0,(short)j, (1+i), (short) (j+1), (2+i)); patriarch.createPicture(anchorP, workbook.addPicture((byte[]) list.get(i).get(keys[j]), HSSFWorkbook.PICTURE_TYPE_JPEG)); }else { Cell cell = rowTwo.createCell(j); cell.setCellValue(list.get(i).get(keys[j]) == null ? " " : list.get(i).get(keys[j]).toString()); cell.setCellStyle(styleTwo); } } } } catch (Exception e) { logger.error("TestController.test6 error:" + e); } return workbook; } }

    WordToEmailUtil 工具类

    public class WordToEmailUtil { //发送人的登录用户名 private static String userName; //发送人的登录密码 private static String pass; //发件人的邮箱地址 private static String from; //服务器地址--主机 private static String host; //端口 private static String port; //协议 private static String protocol; public static final Logger logger = LoggerFactory.getLogger(WordToEmailUtil.class); static { Properties prop = new Properties(); try { prop.load(WordToEmailUtil.class.getResourceAsStream("/mailConfig.properties")); } catch (IOException e) { logger.info("加载邮箱配置文件失败", e); } userName = prop.getProperty("e.account"); pass = prop.getProperty("e.pass"); from = prop.getProperty("e.from"); host = prop.getProperty("e.host"); port = prop.getProperty("e.port"); protocol = prop.getProperty("e.protocol"); } //用户名密码验证,需要实现抽象类Authenticator的抽象方法PasswordAuthentication static class MyAuthenricator extends Authenticator { String u = null; String p = null; public MyAuthenricator(String u, String p) { this.u = u; this.p = p; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(u, p); } } /** * @param inputStream 文件流,即处理好的输入流文件 * @param subject 邮件主题 * @param htmlContent 邮件正文内容 * @param to 发给谁 (接收人和抄送人都在系统变量里直接配置了,多个的话以‘,’分隔) * @param cc 抄送给谁? * @param fujian 附件的名字加后缀,例:我的文件.xls 或者 例子: 我的文件.doc 等等格式文件!!! * @author huaiyan */ public static boolean sendEmailToSomeOne(InputStream inputStream, String subject, String htmlContent, String to, String cc, String fujian) { boolean flag = false; try { logger.info("WordToEmailUtil.sendEmailToSomeOne info={}", "开始调用工具类WordToEmailUtil,开始发送邮件!"); long currentTimeMillis = System.currentTimeMillis(); //加载配置文件 Properties properties = new Properties(); //设置主机地址 properties.setProperty("mail.smtp.host", host); //设置邮件协议 properties.setProperty("mail.transport.protocol", protocol); //进行认证 properties.setProperty("mail.smtp.auth", "true"); // 端口识别 properties.setProperty("mail.smtp.port", port); //ssl是否启用 //使用SSL,企业邮箱必需! properties.setProperty("mail.smtp.ssl.enable", "true"); //防止报 Could not connect to SMTP host这种错 properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); //创建session Session session = Session.getDefaultInstance(properties, new MyAuthenricator(userName, pass)); //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态,false表示在控制台不可看,true代表在控制台可看 // session.setDebug(true); //创建邮件对象 MimeMessage message = new MimeMessage(session); //邮件的主标题 if (!StringUtil.isEmpty(subject)) { message.setSubject(subject); } else { message.setSubject("这是邮件主题!"); } //邮件发送日期 message.setSentDate(new Date()); //指明邮件的发件人 message.setFrom(new InternetAddress(userName)); //多个收件人,收件人是不能为空,为空的话,邮件不进行发送!直接返回false String type = ""; boolean toSomeOne = isSplit(to, message, type); if (!toSomeOne) { logger.info("WordToEmailUtil.sendEmailToSomeOne info={}", "收件人邮箱为空,邮件被动终止!"); return flag; } type = "369"; //多个抄送人,与接收人一样的逻辑,但是抄送人可以为空! isSplit(cc, message, type); Multipart multipart = new MimeMultipart(); //添加邮件正文 BodyPart contentBodyPart = new MimeBodyPart(); if (!StringUtil.isEmpty(htmlContent)) { //防止乱码 contentBodyPart.setContent(htmlContent, "text/html;charset=UTF-8"); } else { contentBodyPart.setContent("这是邮件正文内容!", "text/html;charset=UTF-8"); } //将正文添加到邮件中 multipart.addBodyPart(contentBodyPart); //inputStream,这是数据源,.doc文件转成流发送,Excel也可以进行 if (!StringUtil.isEmpty(inputStream)) { DataSource datasource = new ByteArrayDataSource(inputStream, "application/msexcel"); //设置第一个附件的数据,如果有多个附件,这里对数据源进行遍历处理即可! MimeBodyPart attch = new MimeBodyPart(); attch.setDataHandler(new DataHandler(datasource)); //文件是否进行重命名,--要加上相应文件的后缀,以附件形式进行发送! String fileName = fujian; //防止乱码,这里进行编码! attch.setFileName(MimeUtility.encodeText(fileName)); //将附件添加上去 multipart.addBodyPart(attch); message.setContent(multipart); //最后进行邮件发送,Transport每次发送成功程序都会帮忙关闭,不需要手动close Transport.send(message, message.getAllRecipients()); logger.info("WordToEmailUtil.sendEmailToSomeOne info={}", "以" + fileName + "作为附件,邮件成功发送到对方!"); long timeMillis = System.currentTimeMillis(); float times = (float) (timeMillis - currentTimeMillis) / 1000; flag = true; logger.info("WordToEmailUtil.sendEmailToSomeOne info={}", "发送邮件完毕,耗时 " + times); } else { //说明附件为空,那就不是这个方法了!!! logger.info("WordToEmailUtil.sendEmailToSomeOne info={}", "数据源文件为空,加载附件失败,发送邮件被动终止!"); return flag; } } catch (Exception e) { logger.error("WordToEmailUtil.sendEmailToSomeOne error={}", "系统异常,数据源或者其他必须参数为空!"); logger.error("WordToEmailUtil.sendEmailToSomeOne error={}", "系统异常,发送邮件被动终止!"); e.printStackTrace(); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } logger.info("WordToEmailUtil.sendEmailToSomeOne info={}", "调用工具类WordToEmailUtil结束,发送邮件完毕"); return flag; } /** * @param SomeOne 收件人或者抄送人 * @param message 附件信息 * @param type 一种判断是收件人还是抄送人的标志 * @return * @throws MessagingException 异常 * @author huaiyan */ private static boolean isSplit(String SomeOne, MimeMessage message, String type) throws MessagingException { if (!StringUtil.isEmpty(SomeOne)) { if (SomeOne.contains(",")) { String[] splits = SomeOne.split(","); // 构建一个群发地址数组 InternetAddress[] adr = new InternetAddress[splits.length]; for (int i = 0; i < splits.length; i++) { adr[i] = new InternetAddress(splits[i]); } // Message的setRecipients方法支持群发。。注意:setRecipients方法是复数和点 到点不一样 //type为空,说明是收件人 if (StringUtil.isEmpty(type)) { message.setRecipients(Message.RecipientType.TO, adr); return true; } else { //说明是抄送人 message.setRecipients(Message.RecipientType.CC, adr); return true; } } else { //说明只有一个接收人或者抄送人 //type不为空,说明是抄送人 if (!StringUtil.isEmpty(type)) { message.setRecipients(Message.RecipientType.CC, SomeOne); return true; } else { //为空,说明是收件人 message.setRecipients(Message.RecipientType.TO, SomeOne); return true; } } } else { //收件人或抄送人为空 return false; } } }
    最新回复(0)