Word转图片功能 - API接口文档

接口概览

接口名称 接口路径 方法 说明
模糊评价报告下载 /admin/stat/report/fuzzyReport GET 下载Word报告,可选转图片
获取报告图片列表 /admin/stat/report/getReportImages GET 获取已转换的图片文件列表
检查转换状态 /admin/stat/report/checkConversionStatus GET 检查文件转换状态

1. 模糊评价报告下载(支持转图片)

接口信息

  • 接口路径: /admin/stat/report/fuzzyReport
  • 请求方法: GET
  • 接口说明: 下载模糊评价报告Word文档,可选择同时转换为图片保存到服务器

请求参数

参数名 类型 必填 说明 示例值
checkTaskId Integer 是 检查任务ID 1
templateId Integer 是 报告模板ID 1
uuid String 否 文件唯一标识,传入则保存文件并转换为图片 abc123

响应说明

  • Content-Type: application/octet-stream
  • 响应体: Word文档二进制流
  • 文件名: 项目名_模板名_模糊评价.docx(URL编码)

服务器端行为

当 uuid 参数为空或不传时:
- 仅返回Word文档供用户下载
- 不保存文件到服务器
- 不进行图片转换

当 uuid 参数有值时:
1. 返回Word文档供用户下载
2. 保存Word文档到服务器:F:\file\estate\reports\{uuid}.docx
3. 后台转换Word为图片:F:\file\estate\reports\images\{uuid}_page_N.png

请求示例

示例1:仅下载(不保存)

curl -o report.docx "http://localhost:8080/admin/stat/report/fuzzyReport?checkTaskId=1&templateId=1"

示例2:下载并转图片

curl -o report.docx "http://localhost:8080/admin/stat/report/fuzzyReport?checkTaskId=1&templateId=1&uuid=abc123"

示例3:JavaScript调用

// 仅下载
window.location.href = '/admin/stat/report/fuzzyReport?checkTaskId=1&templateId=1';

// 下载并转图片
const uuid = generateUUID(); // 生成唯一标识
window.location.href = `/admin/stat/report/fuzzyReport?checkTaskId=1&templateId=1&uuid=${uuid}`;

// 稍后查询图片列表
setTimeout(() => {
    fetch(`/admin/stat/report/getReportImages?uuid=${uuid}`)
        .then(res => res.json())
        .then(data => console.log('图片列表:', data));
}, 5000); // 等待5秒让转换完成

2. 获取报告图片列表

接口信息

  • 接口路径: /admin/stat/report/getReportImages
  • 请求方法: GET
  • 接口说明: 根据UUID获取已转换的图片文件列表

请求参数

参数名 类型 必填 说明 示例值
uuid String 是 文件唯一标识 abc123

响应格式

{
    "code": 0,
    "message": "success",
    "data": [
        "abc123_page_1.png",
        "abc123_page_2.png",
        "abc123_page_3.png"
    ]
}

响应字段说明

字段名 类型 说明
code Integer 状态码,0表示成功
message String 响应消息
data Array 图片文件名列表,按页码排序

请求示例

curl "http://localhost:8080/admin/stat/report/getReportImages?uuid=abc123"

JavaScript示例

async function getReportImages(uuid) {
    const response = await fetch(`/admin/stat/report/getReportImages?uuid=${uuid}`);
    const result = await response.json();

    if (result.code === 0) {
        console.log('图片列表:', result.data);
        // 构建完整URL
        const imageUrls = result.data.map(filename =>
            `/files/reports/images/${filename}`
        );
        return imageUrls;
    } else {
        console.error('获取图片列表失败:', result.message);
        return [];
    }
}

// 使用示例
getReportImages('abc123').then(urls => {
    urls.forEach((url, index) => {
        console.log(`第${index + 1}页: ${url}`);
    });
});

3. 检查转换状态

接口信息

  • 接口路径: /admin/stat/report/checkConversionStatus
  • 请求方法: GET
  • 接口说明: 检查Word文档转换为图片的状态

请求参数

参数名 类型 必填 说明 示例值
uuid String 是 文件唯一标识 abc123

响应格式

{
    "code": 0,
    "message": "success",
    "data": {
        "uuid": "abc123",
        "wordFileExists": true,
        "imageCount": 3,
        "conversionCompleted": true
    }
}

响应字段说明

字段名 类型 说明
code Integer 状态码,0表示成功
message String 响应消息
data Object 转换状态对象
data.uuid String 文件唯一标识
data.wordFileExists Boolean Word文件是否存在
data.imageCount Integer 已转换的图片数量
data.conversionCompleted Boolean 转换是否完成(imageCount > 0)

请求示例

curl "http://localhost:8080/admin/stat/report/checkConversionStatus?uuid=abc123"

JavaScript示例

async function checkConversionStatus(uuid) {
    const response = await fetch(`/admin/stat/report/checkConversionStatus?uuid=${uuid}`);
    const result = await response.json();

    if (result.code === 0) {
        const status = result.data;
        console.log(`UUID: ${status.uuid}`);
        console.log(`Word文件存在: ${status.wordFileExists}`);
        console.log(`图片数量: ${status.imageCount}`);
        console.log(`转换完成: ${status.conversionCompleted}`);
        return status;
    } else {
        console.error('检查状态失败:', result.message);
        return null;
    }
}

// 轮询检查转换状态
async function waitForConversion(uuid, maxAttempts = 10, interval = 2000) {
    for (let i = 0; i < maxAttempts; i++) {
        const status = await checkConversionStatus(uuid);

        if (status && status.conversionCompleted) {
            console.log('转换完成!');
            return status;
        }

        console.log(`等待转换完成... (${i + 1}/${maxAttempts})`);
        await new Promise(resolve => setTimeout(resolve, interval));
    }

    console.error('转换超时');
    return null;
}

// 使用示例
waitForConversion('abc123').then(status => {
    if (status) {
        console.log(`成功转换${status.imageCount}张图片`);
    }
});

完整使用流程示例

场景:下载报告并获取图片

// 1. 生成UUID
const uuid = generateUUID(); // 或使用 crypto.randomUUID()

// 2. 下载报告(同时触发转换)
downloadReport(uuid);

// 3. 等待转换完成
const status = await waitForConversion(uuid);

// 4. 获取图片列表
if (status && status.conversionCompleted) {
    const images = await getReportImages(uuid);
    displayImages(images);
}

// 辅助函数
function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function downloadReport(uuid) {
    const url = `/admin/stat/report/fuzzyReport?checkTaskId=1&templateId=1&uuid=${uuid}`;
    window.location.href = url;
}

async function waitForConversion(uuid, maxAttempts = 10, interval = 2000) {
    for (let i = 0; i < maxAttempts; i++) {
        const response = await fetch(`/admin/stat/report/checkConversionStatus?uuid=${uuid}`);
        const result = await response.json();

        if (result.code === 0 && result.data.conversionCompleted) {
            return result.data;
        }

        await new Promise(resolve => setTimeout(resolve, interval));
    }
    return null;
}

async function getReportImages(uuid) {
    const response = await fetch(`/admin/stat/report/getReportImages?uuid=${uuid}`);
    const result = await response.json();
    return result.code === 0 ? result.data : [];
}

function displayImages(imageFiles) {
    const container = document.getElementById('image-container');
    imageFiles.forEach(filename => {
        const img = document.createElement('img');
        img.src = `/files/reports/images/${filename}`;
        img.alt = filename;
        container.appendChild(img);
    });
}

错误码说明

错误码 说明 解决方案

| 0 | 成功 | - |
| 非0 | 失败 | 查看message字段获取详细错误信息 |

常见错误

1. 任务不存在
json { "code": 1001, "message": "任务不存在" }
解决方案: 检查checkTaskId是否正确

2. 文件不存在
json { "code": 0, "message": "success", "data": [] }
解决方案:
- 检查uuid是否正确
- 确认是否已调用下载接口并传入uuid参数
- 等待转换完成(通常需要几秒钟)

3. 转换失败
- 查看服务器日志,搜索关键词:"Word转图片失败"
- 检查服务器磁盘空间
- 检查系统字体是否完整


性能说明

转换时间

文档页数 预计转换时间 图片大小(300 DPI)
1-5页 2-5秒 约500KB/页
6-10页 5-10秒 约500KB/页
11-20页 10-20秒 约500KB/页

并发限制

  • 建议同时转换任务数:≤ 5个
  • 超过限制可能导致服务器响应变慢

存储空间

  • Word文档:约100-500KB/文档
  • PNG图片:约500KB/页(300 DPI)
  • 建议定期清理旧文件

安全说明

访问控制

  • 所有接口已添加 @IgnoreAuth 注解,无需认证
  • 生产环境建议添加认证机制

UUID安全

  • UUID应由客户端生成,确保唯一性
  • 避免使用可预测的UUID(如连续数字)
  • 建议使用标准UUID格式

文件访问

  • 图片文件存储在服务器本地
  • 需要配置静态资源映射才能通过HTTP访问
  • 建议添加访问权限控制

配置静态资源访问

Spring Boot配置

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${file.upload.dir}")
    private String uploadDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射图片访问路径
        registry.addResourceHandler("/files/reports/images/**")
                .addResourceLocations("file:" + uploadDir + "/reports/images/");
    }
}

访问示例

http://localhost:8080/files/reports/images/abc123_page_1.png

附录

UUID生成方法

Java:
java String uuid = UUID.randomUUID().toString().replace("-", "");

JavaScript:
javascript const uuid = crypto.randomUUID().replace(/-/g, '');

Python:
python import uuid uuid_str = str(uuid.uuid4()).replace('-', '')

图片预览HTML示例

<!DOCTYPE html>
<html>
<head>
    <title>报告预览</title>
    <style>
        .image-container {
            max-width: 800px;
            margin: 0 auto;
        }
        .page-image {
            width: 100%;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="image-container" id="images"></div>

    <script>
        const uuid = 'abc123'; // 替换为实际UUID

        fetch(`/admin/stat/report/getReportImages?uuid=${uuid}`)
            .then(res => res.json())
            .then(result => {
                if (result.code === 0) {
                    const container = document.getElementById('images');
                    result.data.forEach((filename, index) => {
                        const img = document.createElement('img');
                        img.src = `/files/reports/images/${filename}`;
                        img.className = 'page-image';
                        img.alt = `第${index + 1}页`;
                        container.appendChild(img);
                    });
                }
            });
    </script>
</body>
</html>