zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Junit 模拟 MockMultipartFile 文件测试

2023-09-14 09:06:15 时间
 //str是图片base64编码
String str = "+a4g9dgl00KLjm7pLDL3Rkcum6Bh43dQfNog/F7quSXTUoLKia/NKa。。。。。"
 String property = System.getProperty("user.dir");


    Base64Util.base64StrToImage(str, property + "\\test.jpg");
    File file = new File(property + "\\test.jpg");
    FileInputStream fileInputStream = new FileInputStream(file);
    MockMultipartFile mfile = new MockMultipartFile(file.getName(), fileInputStream);
    mfile  就是模拟的 MockMultipartFile 文件了 
/**
         * base64编码字符串转换为图片
         * @param imgStr base64编码字符串
         * @param path 图片路径
         * @return
         */
        public static boolean base64StrToImage(String imgStr, String path) {
            if (imgStr == null) {
                return false;}
            Base64.Decoder decoder = Base64.getDecoder();
    
            try {
                // 解密
                byte[] b = decoder.decode(imgStr);
                // 处理数据
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {
                        b[i] += 256;
                    }
                }
                //文件夹不存在则自动创建
                File tempFile = new File(path);
                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdirs();
                }
                OutputStream out = new FileOutputStream(tempFile);
                out.write(b);
                out.flush();
                out.close();
                return true;
            } catch (Exception e) {
                return false;
            }
        }