一个基于 HTTP API 的标签打印服务
该服务是试验性,仅用于测试环境 ……
https://www.yi-label.com/yilabel/printserver-v1.html?yixid=……&dataid=……
1. 上传模板文件
- 功能:将标签模板文件(如
test02.yix
)上传到服务器。 - API 接口:curl 示例
curl -X POST -F "template=@test02.yix" http://apiv2.yi-label.com:3000/upload-template
- 返回数据:
yixid
:模板文件的唯一标识符,用于后续操作。- 示例:
{"yixid":"5faa32de-3b45-43f3-8633-a7ddae75d47e"}
2. 上传 JSON 数据文件
- 功能:将 JSON 数据文件(如
data.json
)上传到服务器。- JSON 数据第一行为数据源Column名称,即易标签软件模板中”编程为(二次开发)” 的内容设置,
- JSON 数据第二行开始为实际打印数据.
- API 接口:curl 示例
curl -X POST -F "data=@data.json" http://apiv2.yi-label.com:3000/upload-data
- 返回数据:
dataId
:数据文件的唯一标识符,用于后续操作。- 示例:
{"dataId":"c2a06477-e2d9-4300-adb2-e8e58cfa4026"}
3. 生成打印链接
- 功能:根据上传的模板文件(
yixid
)和数据文件(dataId
),生成一个用于标签打印的链接。 - 链接格式:
https://www.yi-label.com/yilabel/printserver-v1.html?yixid=<yixid>&dataid=<dataid>
- 示例:https://www.yi-label.com/yilabel/printserver-v1.html?yixid=5faa32de-3b45-43f3-8633-a7ddae75d47e&dataid=c2a06477-e2d9-4300-adb2-e8e58cfa4026
- 用途:用户可以通过该链接访问打印页面,将模板和数据结合生成标签并打印。
4. 服务流程总结
- 上传模板:通过
upload-template
接口上传模板文件,获取yixid
。 - 上传数据:通过
upload-data
接口上传 JSON 数据文件,获取dataId
。 - 生成打印链接:将
yixid
和dataId
拼接到打印链接中,用户访问该链接即可进行标签打印。
5. 适用场景
- 标签打印:适用于需要根据模板和数据动态生成标签的场景,如物流标签、产品标签等。
- 自动化流程:通过 API 实现模板和数据的自动化上传与打印链接生成。
- 灵活性与可扩展性:支持自定义模板和数据,适用于多种业务需求。
6. 技术要点
- HTTP API:使用
POST
方法上传文件,返回 JSON 格式的响应数据。 - 唯一标识符:
yixid
和dataId
用于标识模板和数据,确保打印链接的唯一性和准确性。 - 链接参数:通过 URL 参数传递
yixid
和dataId
,实现动态生成打印页面。
Python web打印示例
import requests
import os
# 上传模板文件
template_file_path = 'test02.yix'
upload_template_url = 'http://apiv2.yi-label.com:3000/upload-template'
if os.path.exists(template_file_path):
with open(template_file_path, 'rb') as template_file:
files = {'template': template_file}
response_template = requests.post(upload_template_url, files=files)
if response_template.status_code == 200:
yixid = response_template.json().get('yixid')
print(f"上传模板成功,yixid: {yixid}")
else:
print(f"上传模板失败,状态码: {response_template.status_code},响应内容: {response_template.text}")
# 上传 JSON 数据文件
data_file_path = 'data2.json'
upload_data_url = 'http://apiv2.yi-label.com:3000/upload-data'
with open(data_file_path, 'rb') as data_file:
files = {'data': data_file}
response_data = requests.post(upload_data_url, files=files)
if response_data.status_code == 200:
dataid = response_data.json().get('dataId')
print(f"上传 JSON 数据文件成功,dataid: {dataid}")
else:
print(f"上传 JSON 数据文件失败,状态码: {response_data.status_code},响应内容: {response_data.text}")
# 调用打印链接
if yixid and dataid:
print_url = f"https://www.yi-label.com/yilabel/printserver-v1.html?yixid={yixid}&dataid={dataid}"
print(f"打印链接: {print_url}")
else:
print("无法生成打印链接,可能是上传过程中出现问题。")
PHP web打印示例
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JavaUploadExample {
private static final String BOUNDARY = "---------------------------1234567890";
private static final String LINE_FEED = "\r\n";
public static void main(String[] args) {
String templateFilePath = "test02.yix";
String uploadTemplateUrl = "http://apiv2.yi-label.com:3000/upload-template";
String yixid = uploadFile(templateFilePath, uploadTemplateUrl, "template");
String dataFilePath = "data2.json";
String uploadDataUrl = "http://apiv2.yi-label.com:3000/upload-data";
String dataid = uploadFile(dataFilePath, uploadDataUrl, "data");
if (yixid != null && dataid != null) {
String printUrl = "https://www.yi-label.com/yilabel/printserver-v1.html?yixid=" + yixid + "&dataid=" + dataid;
System.out.println("打印链接: " + printUrl);
} else {
System.out.println("无法生成打印链接,可能是上传过程中出现问题。");
}
}
private static String uploadFile(String filePath, String uploadUrl, String fileParamName) {
File file = new File(filePath);
if (!file.exists()) {
System.out.println("文件 " + filePath + " 不存在。");
return null;
}
try {
URL url = new URL(uploadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream outputStream = connection.getOutputStream();
StringBuilder sb = new StringBuilder();
sb.append("--").append(BOUNDARY).append(LINE_FEED);
sb.append("Content-Disposition: form-data; name=\"").append(fileParamName).append("\"; filename=\"")
.append(file.getName()).append("\"").append(LINE_FEED);
sb.append("Content-Type: application/octet-stream").append(LINE_FEED);
sb.append(LINE_FEED);
outputStream.write(sb.toString().getBytes());
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.write((LINE_FEED + "--" + BOUNDARY + "--" + LINE_FEED).getBytes());
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Scanner scanner = new Scanner(connection.getInputStream());
StringBuilder response = new StringBuilder();
while (scanner.hasNextLine()) {
response.append(scanner.nextLine());
}
scanner.close();
JsonObject jsonObject = JsonParser.parseString(response.toString()).getAsJsonObject();
String id = null;
if (fileParamName.equals("template")) {
id = jsonObject.get("yixid").getAsString();
System.out.println("上传模板成功,yixid: " + id);
} else if (fileParamName.equals("data")) {
id = jsonObject.get("dataId").getAsString();
System.out.println("上传 JSON 数据文件成功,dataid: " + id);
}
return id;
} else {
Scanner scanner = new Scanner(connection.getErrorStream());
StringBuilder errorResponse = new StringBuilder();
while (scanner.hasNextLine()) {
errorResponse.append(scanner.nextLine());
}
scanner.close();
System.out.println("上传失败,状态码: " + responseCode + ",响应内容: " + errorResponse.toString());
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
VBA 打印示例
宏会自动将数据保存为JSON文件,并上传 模板文件 和 .json 文件上传,并打开打印链接。
Option Explicit
' 声明 ShellExecute API 函数
Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
Sub ExportAndPrint()
Dim ws As Worksheet
Dim lastRow As Long, lastCol As Long
Dim i As Long, j As Long
Dim json As String
Dim filePath As String
Dim fileNum As Integer
Dim excelFileName As String
Dim jsonFileName As String
Dim yixFileName As String
Dim curlCommand As String
Dim resultFile As String
Dim yixid As String
Dim dataId As String
Dim response As String
Dim link As String
' 设置工作表
Set ws = ThisWorkbook.Sheets(1) ' 假设你要导出第一个工作表的数据
' 获取数据的最后一行和最后一列
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
' 初始化JSON字符串
json = "["
' 添加表头行
json = json & "["
For j = 1 To lastCol
json = json & """" & ws.Cells(1, j).Value & """"
If j < lastCol Then json = json & ","
Next j
json = json & "],"
' 添加数据行
For i = 2 To lastRow
json = json & "["
For j = 1 To lastCol
json = json & """" & ws.Cells(i, j).Value & """"
If j < lastCol Then json = json & ","
Next j
json = json & "]"
If i < lastRow Then json = json & ","
Next i
json = json & "]"
' 获取Excel文件的路径和名称
excelFileName = ThisWorkbook.FullName ' 获取完整路径
jsonFileName = Left(excelFileName, InStrRev(excelFileName, ".") - 1) & ".json" ' 替换扩展名为.json
yixFileName = Left(excelFileName, InStrRev(excelFileName, ".") - 1) & ".yix" ' 替换扩展名为.yix
' 保存JSON到文件
fileNum = FreeFile
Open jsonFileName For Output As #fileNum
Print #fileNum, json
Close #fileNum
' 上传模板文件 (.yix) 并获取 yixid
curlCommand = "curl -X POST -F ""template=@" & yixFileName & """ http://apiv2.yi-label.com:3000/upload-template"
resultFile = Left(excelFileName, InStrRev(excelFileName, ".") - 1) & "_response.txt"
Shell "cmd.exe /c " & curlCommand & " > " & resultFile, vbHide
' 等待命令执行完成
Application.Wait Now + TimeValue("00:00:05")
' 读取返回的 yixid
fileNum = FreeFile
Open resultFile For Input As #fileNum
response = Input$(LOF(fileNum), fileNum)
Close #fileNum
yixid = ParseJSON(response, "yixid") ' 解析返回的 JSON 数据
' 上传JSON文件并获取 dataId
curlCommand = "curl -X POST -F ""data=@" & jsonFileName & """ http://apiv2.yi-label.com:3000/upload-data"
Shell "cmd.exe /c " & curlCommand & " > " & resultFile, vbHide
' 等待命令执行完成
Application.Wait Now + TimeValue("00:00:05")
' 读取返回的 dataId
fileNum = FreeFile
Open resultFile For Input As #fileNum
response = Input$(LOF(fileNum), fileNum)
Close #fileNum
dataId = ParseJSON(response, "dataId") ' 解析返回的 JSON 数据
' 生成链接
link = "https://www.yi-label.com/yilabel/printserver-v1.html?yixid=" & yixid & "&dataid=" & dataId
' 弹出消息框并打开链接
If MsgBox("请访问以下链接:" & vbCrLf & link & vbCrLf & "点击“确定”打开链接。", vbOKCancel + vbInformation, "打开链接") = vbOK Then
ShellExecute 0, "open", link, "", "", 1
End If
End Sub
Function ParseJSON(json As String, key As String) As String
' 从 JSON 字符串中解析指定 key 的值
Dim startPos As Long
Dim endPos As Long
Dim searchKey As String
searchKey = """" & key & """:"""
startPos = InStr(json, searchKey)
If startPos > 0 Then
startPos = startPos + Len(searchKey)
endPos = InStr(startPos, json, """")
If endPos > startPos Then
ParseJSON = Mid(json, startPos, endPos - startPos)
End If
End If
End Function