代码示例 - 多语言压缩代码

按语言和场景分类的压缩API代码示例,覆盖Python、Node.js、Java、Go、curl,附带AI数据预处理、批量回调、加密压缩等最佳实践

Python 示例

使用 requests 库调用压缩API,支持单文件、批量与异步三种模式

单文件压缩

import requests

resp = requests.post(
    "https://api.uglypear.com/v1/compress",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    files={"file": open("input.pdf", "rb")},
    data={"quality": "high"}
)
print(resp.json())

批量压缩

import requests

files = [("files", open(f, "rb")) for f in ["a.pdf", "b.pdf", "c.pdf"]]
resp = requests.post(
    "https://api.uglypear.com/v1/batch/compress",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    files=files,
    data={"quality": "medium", "callback_url": "https://yourapp.com/callback"}
)
print(resp.json())

异步压缩

import asyncio
import aiohttp

async def compress(path):
    async with aiohttp.ClientSession() as session:
        with open(path, "rb") as f:
            data = aiohttp.FormData()
            data.add_field("file", f)
            data.add_field("quality", "high")
            async with session.post(
                "https://api.uglypear.com/v1/compress",
                headers={"Authorization": "Bearer YOUR_API_KEY"},
                data=data
            ) as resp:
                return await resp.json()

asyncio.run(compress("input.pdf"))

Node.js 示例

使用 axios + form-data 实现流式上传与批量处理

流式压缩

const fs = require("fs");
const FormData = require("form-data");
const axios = require("axios");

const form = new FormData();
form.append("file", fs.createReadStream("input.pdf"));
form.append("quality", "high");

axios.post("https://api.uglypear.com/v1/compress", form, {
    headers: {
        ...form.getHeaders(),
        Authorization: "Bearer YOUR_API_KEY"
    }
}).then(res => console.log(res.data));

批量处理

const fs = require("fs");
const FormData = require("form-data");
const axios = require("axios");

const form = new FormData();
["a.pdf", "b.pdf", "c.pdf"].forEach(f =>
    form.append("files", fs.createReadStream(f))
);
form.append("quality", "medium");

axios.post("https://api.uglypear.com/v1/batch/compress", form, {
    headers: { ...form.getHeaders(), Authorization: "Bearer YOUR_API_KEY" }
}).then(res => console.log(res.data));

Java 示例

使用 OkHttp 发起 multipart 上传压缩请求

OkHttpClient client = new OkHttpClient();

RequestBody body = new MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart("file", "input.pdf",
        RequestBody.create(new File("input.pdf"),
            MediaType.parse("application/pdf")))
    .addFormDataPart("quality", "high")
    .build();

Request request = new Request.Builder()
    .url("https://api.uglypear.com/v1/compress")
    .header("Authorization", "Bearer YOUR_API_KEY")
    .post(body)
    .build();

try (Response response = client.newCall(request).execute()) {
    System.out.println(response.body().string());
}

Go 示例

使用标准库 net/http 与 mime/multipart 构建请求

package main

import (
    "bytes"
    "io"
    "mime/multipart"
    "net/http"
    "os"
)

func main() {
    file, _ := os.Open("input.pdf")
    defer file.Close()

    var buf bytes.Buffer
    writer := multipart.NewWriter(&buf)
    part, _ := writer.CreateFormFile("file", "input.pdf")
    io.Copy(part, file)
    writer.WriteField("quality", "high")
    writer.Close()

    req, _ := http.NewRequest("POST",
        "https://api.uglypear.com/v1/compress", &buf)
    req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
    req.Header.Set("Content-Type", writer.FormDataContentType())

    resp, _ := http.DefaultClient.Do(req)
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    println(string(body))
}

curl 示例

命令行快速调用压缩API,适合脚本与自动化测试

curl -X POST https://api.uglypear.com/v1/compress \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@input.pdf" \
  -F "quality=high"

按场景分类的最佳实践

针对典型业务场景的推荐集成方式

AI数据预处理管道集成

在数据入库前调用压缩API对文档/图像预处理,降低存储占用,再按需解压供模型训练使用,加速读取链路。

# 管道集成:入库前压缩
result = comp.compress_file("dataset/doc.pdf", quality="high")
upload_to_storage(result.output_path)

批量压缩+回调通知

批量接口异步处理,任务完成后向 callback_url 推送结果,避免长连接等待。

resp = requests.post(
    "https://api.uglypear.com/v1/batch/compress",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    files=files,
    data={"callback_url": "https://yourapp.com/callback"}
)

带密码的加密压缩

对敏感文件附加 password 参数,服务端加密压缩,保障传输与存储安全。

curl -X POST https://api.uglypear.com/v1/compress \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@input.pdf" \
  -F "password=YourStrongPass"

大文件分块上传压缩

对超大文件先分块上传,再触发整体压缩,避免单次请求超时,提升成功率。

// 分块上传 + 触发压缩
for (const chunk of chunks) {
    await uploadChunk(chunk);
}
await axios.post("https://api.uglypear.com/v1/compress",
    { upload_id, quality: "high" }, { headers });

GitHub 仓库

更多完整示例项目即将开源

uglypear-compressor-examples

包含 Python、Node.js、Java、Go、curl 完整可运行示例项目,即将开源。如需提前获取,请联系技术支持。

联系我们

查看完整API文档

查阅接口参数、错误码与在线调试器,快速掌握压缩API的全部能力

查看API文档 快速开始 下载SDK