File相关_multipartFile_复制_白名单

本文详细介绍了文件上传路径转码对比、目录遍历漏洞防御方法,包括对用户输入的验证,使用file API时的注意事项,以及如何利用Java NIO和Apache Commons IO高效复制文件。

//文件上传路径   转码比较
目录遍历漏洞防御方法
1.对用户的输入进行验证,特别是路径替代字符如“../”和“~/”。

//使用file 时要注意
file的很多api 需要boolean的返回值来验证成功失败
//从request中获取multipartFile
MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
multipartFile = multipartRequest.getFile("xxxFile");
multipartRequest.getFile("file").getSize();
//multipartFile 转 file
multipartFile.transferTo(uploadFile);
 //直接读出文件中的每一行 jdk自带
Files.lines(Paths.get("d:/aa/aa.java")).forEach(System.out::println);

//前台<img标签>访问url路径 ,以流的形式返回,可以在浏览器渲染成图片
@RequestMapping(value = "/res/{key}.{resType}")
请求路径通过尾缀区分
//File复制
1.-Java NIO包括transferFrom方法,根据文档应该比文件流复制的速度更快
private static void copyFileUsingFileChannels(File source, File dest) throws IOException {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
inputChannel.close();
outputChannel.close();
}
}
2.使用Commons IO复制效率不低 - 最方便
private static void copyFileUsingApacheCommonsIO(File source, File dest)
throws IOException {
FileUtils.copyFile(source, dest);
}

 

java.lang.UnsupportedOperationException: Provided data element number (1049024) should be multiple of the Mat channels count (3) 报错了 /** * ocr配置 */ @PostConstruct public void initOcrEngine() { tesseract = new Tesseract(); //语言包路径和支持语言 tesseract.setDatapath(tessDataPath); tesseract.setLanguage("eng+chi_sim"); tesseract.setPageSegMode(6); // 完全自动页面分割模式 tesseract.setOcrEngineMode(2); // LSTM引擎 tesseract.setTessVariable("preserve_interword_spaces", "1"); } /** * OCR识别图片内容 */ private String extractImageText(MultipartFile file) { try (InputStream is = file.getInputStream()) { BufferedImage image = ImageIO.read(is); if (image == null) { return MessageUtils.message("Image.parsing.failed"); } Mat opencvMat = bufferedImageToMat(image); Mat processedMat = preprocessImage(opencvMat); BufferedImage processedImage = matToBufferedImage(processedMat); // BufferedImage processedImage = preprocessImage(image); String result = tesseract.doOCR(processedImage); result = postProcess(result); result = result.replaceAll("\\s+", " ").trim(); System.out.println("图片内容:\n" + result); return result; } catch (Exception e) { e.printStackTrace(); return MessageUtils.message("file.read.picture.error"); } } // 核心图像预处理 private Mat preprocessImage(Mat image) { // 1. 尺寸检查(确保300+ DPI) if (image.rows() < 300 || image.cols() < 300) { Mat resized = new Mat(); Imgproc.resize(image, resized, new Size(image.cols()*1.5, image.rows()*1.5), 0, 0, Imgproc.INTER_LINEAR); image = resized; } // 2. 灰度化 + 二值化 Mat gray = new Mat(); Imgproc.cvtColor(image, gray, Imgproc.COLOR_BGR2GRAY); Imgproc.threshold(gray, gray, 0, 255, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU); // 3. 文本区域聚焦(可选) Mat roi = detectTextRegion(gray); return roi.empty() ? gray : roi; } // 文本区域检测 private Mat detectTextRegion(Mat binaryImage) { // 1. 使用正确的轮廓存储类型(List<MatOfPoint>) List<MatOfPoint> contours = new ArrayList<>(); Mat hierarchy = new Mat(); // 2. 正确调用findContours(OpenCV 4.x API) Imgproc.findContours( binaryImage, contours, // 正确类型 hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE ); // 3. 寻找最大轮廓 double maxArea = 0; Rect maxRect = null; // 初始化为null更安全 // 4. 正确遍历轮廓列表 for (MatOfPoint contour : contours) { double area = Imgproc.contourArea(contour); if (area > maxArea) { maxArea = area; maxRect = Imgproc.boundingRect(contour); } } // 5. 安全返回结果 return (maxRect != null) ? new Mat(binaryImage, maxRect) : new Mat(); } // 文本后处理 private String postProcessText(String text) { // 1. 清理OCR常见噪声 text = text.replaceAll("[^\\p{L}\\p{Nd}.,:;!?@#$%&*()_+=\\-\\s]", "") .replaceAll("\\s+", " ") .trim(); // 2. 结构化数据提取(示例:提取日期) String datePattern = "\\d{4}[-/年]\\d{1,2}[-/月]\\d{1,2}日?"; java.util.regex.Matcher matcher = java.util.regex.Pattern .compile(datePattern).matcher(text); return matcher.find() ? "检测到日期: " + matcher.group() + "\n全文:\n" + text : text; } // 图像格式转换工具 private Mat bufferedImageToMat(BufferedImage bi) { Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3); byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData(); mat.put(0, 0, data); return mat; } private BufferedImage matToBufferedImage(Mat mat) { int type = (mat.channels() == 1) ? BufferedImage.TYPE_BYTE_GRAY : BufferedImage.TYPE_3BYTE_BGR; BufferedImage image = new BufferedImage(mat.cols(), mat.rows(), type); byte[] data = new byte[mat.cols() * mat.rows() * mat.channels()]; mat.get(0, 0, data); System.arraycopy(data, 0, ((DataBufferByte) image.getRaster().getDataBuffer()).getData(), 0, data.length); return image; }
最新发布
07-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值