工具方法
MultipartFile转File
获取文件流
public static File multipartFileToFile(MultipartFile file) throws Exception {
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
return toFile;
}
//获取流文件
private static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
删除本地临时生成的文件
public static void delteTempFile(File file) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
去除html标签(保留换行)
public static String toPlainText(String html)
{
if (StringUtils.isEmpty(html)){
return "";
}
Document document = Jsoup.parse(html);
Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);
document.outputSettings(outputSettings);
document.select("br").append("\\n");
document.select("p").prepend("\\n");
final String newHtml = document.html().replaceAll("\\\\n", "\n");
final String plainText = Jsoup.clean(newHtml, "", Whitelist.none(), outputSettings);
final String result = StringEscapeUtils.unescapeHtml(plainText.trim());
return result;
}
判断这个对象是否有空值
/**
* 判断这个对象是否有空值
* @param object
* @throws Exception
*/
public static boolean isField(Object object)throws Exception{
Class materual = (Class) object.getClass();
Field[] fs = materual.getDeclaredFields();
int i=0;
for (Field f :fs){
i++;
f.setAccessible(true);
Object val = f.get(object);
System.out.println(val);
//如果必选字段没值或空则返回false
if (val==null||val.equals("")){
return false;
}
//3代表这个对象有多少属性,如果三个属性都不为空则返回TRUE
if(i>=3){
return true;
}
}
return true;
}
通过lanmuda获取字符串的中文
public static String getChinese(String paramValue) {
String regex = "([\u4e00-\u9fa5]+)";
String str = "";
Matcher matcher = Pattern.compile(regex).matcher(paramValue);
while (matcher.find()) {
str+= matcher.group(0);
}
return str;
}
数据库文件上传和获取
先建一张文件表
DROP TABLE IF EXISTS `task_file`;
CREATE TABLE `task_file` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
`file_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件名',
`file_byte` mediumblob NULL COMMENT '文件流',
`suffix` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件后缀',
`size` double(10, 2) NULL DEFAULT NULL COMMENT '文件大小',
`create_by` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '创建者',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`update_by` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '更新者',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 115 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '任务图片' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
文件表的实体类和方法
建完表后先写好文件表的实体类和增删改查接口
注意存储文件流的参数需要 byte[] 类型
/** 文件流 */
private byte[] fileByte;
上传方法
public AjaxResult upLoad(MultipartFile file) throws Exception {
TaskFile taskFile = new TaskFile();//文件表的实体类
byte[] filePath= FileCopyUtils.copyToByteArray(file.getInputStream());//将文件流存入字节数组
taskFile.setFileByte(filePath);
taskFile.setFileName(file.getOriginalFilename());
BigDecimal b = new BigDecimal((Double.valueOf(file.getSize())/1000));
double size = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//存文件大小
taskFile.setSize(size);
taskFile.setSuffix(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
taskFileService.insertTaskFile(taskFile);//增加接口(自己写)
return AjaxResult.success(taskFile.getId());//新增完后取自增id
}
查看文件流
当文件流存储到数据库时,操作文件就是相当于增删改查了,其他的方法就不写了
public byte[] selectOneFile(Long id){
byte[] fileByte = taskFileService.selectTaskFileById(id).getFileByte();
return fileByte;
}
生成二维码
public void upload(String str , HttpServletResponse response) throws IOException {
// 设置响应流信息
response.setContentType("image/jpg");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
OutputStream stream = response.getOutputStream();
//获取一个二维码图片
BitMatrix bitMatrix = CommonUtils.createCode(str);//将 str 字符串存到二维码中
//以流的形式输出到前端
MatrixToImageWriter.writeToStream(bitMatrix , "jpg" , stream);
}
通过sql将汉字转首拼(需要编写mysql函数)
先获取26个首字母
CREATE DEFINER=`root`@`000.000.%.%` FUNCTION `fristPinyin`(P_NAME VARCHAR(255)) RETURNS varchar(255) CHARSET utf8
DETERMINISTIC
BEGIN
DECLARE V_RETURN VARCHAR(255);
SET V_RETURN = ELT(INTERVAL(CONV(HEX(left(CONVERT(P_NAME USING gbk),1)),16,10),
0xB0A1,0xB0C5,0xB2C1,0xB4EE,0xB6EA,0xB7A2,0xB8C1,0xB9FE,0xBBF7,
0xBFA6,0xC0AC,0xC2E8,0xC4C3,0xC5B6,0xC5BE,0xC6DA,0xC8BB,
0xC8F6,0xCBFA,0xCDDA,0xCEF4,0xD1B9,0xD4D1),
'A','B','C','D','E','F','G','H','J','K','L','M','N','O','P','Q','R','S','T','W','X','Y','Z');
RETURN V_RETURN;
End
然后循环字符串取出首拼
CREATE DEFINER=`root`@`000.000.%.%` FUNCTION `pinyin`(P_NAME VARCHAR(255)) RETURNS varchar(255) CHARSET utf8
BEGIN
DECLARE V_COMPARE VARCHAR(255);
DECLARE V_RETURN VARCHAR(255);
DECLARE I INT;
SET I = 1;
SET V_RETURN = '';
while I < LENGTH(P_NAME) do
SET V_COMPARE = SUBSTR(P_NAME, I, 1);
IF (V_COMPARE != '') THEN
#SET V_RETURN = CONCAT(V_RETURN, ',', V_COMPARE);
SET V_RETURN = CONCAT(V_RETURN, fristPinyin(V_COMPARE));
#SET V_RETURN = fristPinyin(V_COMPARE);
END IF;
SET I = I + 1;
end while;
IF (ISNULL(V_RETURN) or V_RETURN = '') THEN
SET V_RETURN = P_NAME;
END IF;
RETURN V_RETURN;
END
因为这个函数在数据量大的时候执行很慢,所以最好额外加一个首拼字段,在数据新增的时候生成首拼,然后查询就可以通过这个字段来查了
insert into 表名
(名称字段,名称首拼字段) values ("中华人民",pinyin("中华人民"))
获取某年某月的天数
SELECT day(LAST_DAY("2021-05-01"))
PDF转图片
直接复制即可用,调用"pdftoIamge"方法,返回图片数据流集合,我直接使用相对路径,"outputFile"参数没用
PS:在Linux系统下要下载"华文宋体.ttf"字体(Linux下没有相对应的中文字体,如果没有中文字体会出现中文变方框的情况),另外这里图片格式使用png
package com.docer.web.utlis;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import com.docer.system.service.impl.SysUserServiceImpl;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
public class PDFToImg {
// 水印透明度
private static float alpha = 0.5f;
// 水印横向位置
private static int positionWidth = 150;
// 水印纵向位置
private static int positionHeight = 300;
// 水印文字字体
private static Font font = new Font("仿宋", Font.BOLD, 26);
// 水印文字颜色
private static Color color = Color.GRAY;
private static final Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);
/**
* 生成pdf的缩略图
* zoom 缩略图显示倍数,1表示不缩放,0.5表示缩小到50%
* @param inputFile 需要生成缩略图的书籍的完整路径
* @param outputFile 生成缩略图的放置路径
*/
public List<byte[]> pdftoIamge(String inputFile, String outputFile) {
float zoom=1f;
List<byte[]> list = null;
Document document = null;
try {
list = new ArrayList(0);
document = new Document();
document.setFile(inputFile);
float rotation = 0;
int maxPages = document.getPageTree().getNumberOfPages();
for (int i = 0; i < maxPages; i++) {
BufferedImage bfimage = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN,Page.BOUNDARY_CROPBOX, rotation, zoom);
bfimage = setGraphics(bfimage);
RenderedImage rendImage = bfimage;
ImageIO.write(rendImage, "png", new File(i+".png"));
bfimage.flush();
File file = new File(i+".png");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] filePath= FileCopyUtils.copyToByteArray(fileInputStream);
list.add(filePath);
PDFToImg.delteTempFile(file);
}
}catch (Exception e) {
e.printStackTrace();
}
if(document!=null){
document.dispose();
}
return list;
}
public BufferedImage setGraphics(BufferedImage bfimage){
Graphics2D g = bfimage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// 5、设置水印文字颜色
g.setColor(color);
// 6、设置水印文字Font
g.setFont(font);
// 7、设置水印文字透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha));
//设置旋转
g.rotate(-Math.PI/6);
// g.drawString("一道科技", 0, (bfimage.getHeight()/2)*1);
// 9、释放资源
g.dispose();
return bfimage;
}
public static File multipartFileToFile(MultipartFile file) throws Exception {
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
return toFile;
}
//获取流文件
private static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除本地临时文件
* @param file
*/
public static void delteTempFile(File file) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
}
字符串转成pdf文件
调用"HtmlToPDF"方法,返回PDF文件数据流
package com.docer.web.utlis;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.springframework.util.FileCopyUtils;
import java.io.*;
import java.nio.charset.Charset;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
public class HtmlToPDF {
public byte[] HtmlToPDF(String str) throws Exception {
String content = content2Html(str);
byte[] bytes = html2Pdf(content);
return bytes;
}
/**
* html转换成pdf文件
*
* @param htmlContent
* @throws Exception
*/
protected byte[] html2Pdf(String htmlContent) throws Exception {
MyFontsProvider fontProvider = new MyFontsProvider();
fontProvider.addFontSubstitute("lowagie", "garamond");
fontProvider.setUseUnicode(true);
byte[] filePath=null;
File dir = new File("./temporary");
if (!dir.exists()) {
dir.mkdir();
}
File pdfFile = new File(dir + "/临时"+ "-" + System.currentTimeMillis() + ".pdf");
//1 打开文件流
Document document = new Document();
FileOutputStream fos = new FileOutputStream(pdfFile);
InputStream is = new ByteArrayInputStream(htmlContent.getBytes(Charset.forName("UTF-8")));
// InputStream cssIs = new ByteArrayInputStream(getCssFile());
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, fos);
//3 打开文档
document.open();
//4 html转为pdf
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is, Charset.forName("UTF-8"),
fontProvider);
} catch (DocumentException | IOException e) {
throw new RuntimeException("转pdf失败~");
} finally {
if (null != writer) {
writer.flush();
}
//5 关闭文档
document.close();
fos.close();
// cssIs.close();
is.close();
writer.close();
}
FileInputStream fileInputStream = new FileInputStream(pdfFile);
filePath= FileCopyUtils.copyToByteArray(fileInputStream);
PDFToImg.delteTempFile(pdfFile);
return filePath;
}
/**
* 获取html
*
* @return
*/
protected String content2Html(String CONTENT) {
String COMPLETE_CONTENT = "<html><head></head><body style=\"font-family: SimSun;\">" + CONTENT + "</body></html>";
String content = COMPLETE_CONTENT;
content = content.replace("<br>", "<br/>");
return content;
}
// /**
// * 获取样式文件
// *
// * @return
// * @throws Exception
// */
// protected byte[] getCssFile() throws Exception {
// FileInputStream fileInputStream = new FileInputStream("src/main/resources/css/editor.css");
// ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// byte[] buffer = new byte[1204];
// int len = 0;
// while ((len = fileInputStream.read(buffer)) != -1) {
// outStream.write(buffer, 0, len);
// }
// fileInputStream.close();
// return outStream.toByteArray();
// }
/**
* 重写 字符设置方法,解决中文乱码问题
*/
public static class MyFontsProvider extends XMLWorkerFontProvider {
@Override
public Font getFont(final String fontname, final String encoding, final boolean embedded, final float size, final int style, final BaseColor color) {
BaseFont bf = null;
try {
bf = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (Exception e) {
}
Font font = new Font(bf, size, style, color);
font.setColor(color);
return font;
}
}
}
base64解码
因为网上的很多都会报错
public static String decodeBase64(String str) throws UnsupportedEncodingException {
String code = str;
byte[] decode = Base64.getMimeDecoder().decode(code);
return new String(decode,ENCODING);
}