You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Photoshop JS通过Socket传文件至Gin服务时文件为nil的问题

问题:Photoshop JS Socket上传文件到Gin服务器时file为nil

你的问题出在手动构造的multipart/form-data请求格式不符合HTTP标准,导致Gin的表单解析器无法正确识别文件部分。下面具体拆解问题点和修正方案:

核心错误点

  1. 边界线格式错误
    multipart请求中,每个表单部分的开头--boundary后面必须紧跟回车换行(\r\n),你当前的代码直接把--boundary和Content-Disposition连在一起,没有分隔换行,服务器无法识别这是一个独立的表单部分。

  2. 内容分隔的换行不规范
    HTTP头和实际内容之间需要用**两个连续的CRLF(\r\n\r\n)**分隔,你只写了单个\n,导致服务器无法区分头部信息和文件内容的边界。

  3. Content-Length计算错误
    你用content.length计算的是字符串字符数,但fContent是二进制文件内容,在JS中以字符串处理时,部分字节可能被转义,导致声明的长度和实际发送的字节数不匹配,服务器解析时会提前终止。

修正后的Photoshop JS代码

conn = new Socket;
reply = "";
// Read file
var f = File(filepath);
f.encoding = 'BINARY';
f.open("r");
var fContent = f.read();
f.close();

// Connect to server
if (conn.open("127.0.0.1:14000", "BINARY")) {
    conn.timeout = 20000;
    boundary = Math.random().toString().substr(2);
    
    // 修正:boundary后加\r\n,头与内容用\r\n\r\n分隔,字段值加双引号避免解析异常
    var partHeader = "--" + boundary + "\r\n" + 
                     'Content-Disposition: form-data; name="file"; filename="' + filename + '.pdf"\r\n' + 
                     "Content-Type: application/octet-stream\r\n\r\n";
    
    // 修正:结束boundary前加\r\n,保证格式闭合正确
    var endBoundary = "\r\n--" + boundary + "--\r\n";
    
    // 修正:计算实际字节数(BINARY编码下每个字符对应一个字节)
    var totalLength = partHeader.length + fContent.length + endBoundary.length;
    
    var cs = "POST /api/v2/items HTTP/1.1\r\n" + 
             "Content-Length: " + totalLength + "\r\n" + 
             "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n" + 
             "Host: 127.0.0.1:14000\r\n" + 
             "User-Agent: Photoshop-Script/1.0\r\n" + 
             "Accept: */*\r\n\r\n" +  // 修正:请求头结束用\r\n\r\n分隔
             partHeader + fContent + endBoundary;
    
    conn.write(cs);
    reply = conn.read(999999);
    conn.close();
    
    if (reply.indexOf("200 OK") > 0) {
        alert("File successfully uploaded!");
    } else {
        throw new Error("Error:" + reply);
    }
} else {
    throw new Error("Can't connect to server");
}

额外说明

  • HTTP协议要求换行必须是\r\n(CRLF),而非单独的\n,多数服务器解析器对这个规则要求严格;
  • 表单字段的name和filename用双引号包裹,能避免特殊字符引发的解析失败;
  • 移除了Expect: 100-continue头,手动构造请求时如果服务器未正确响应该头,可能导致请求卡住,若需保留请确保服务器支持该特性。

内容的提问来源于stack exchange,提问作者Adrien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:13:05