将文件从 Javascript 套接字 (Ps) 上传到 Golang API (Gin Gonic)

Upload file from Javascript Socket (Ps) to Golang API (Gin Gonic)

我正在尝试从 photoshop 脚本 (javascript) 将文件上传到我的服务器 (Golang)

这是读取服务器上文件的服务:

func Post(c *gin.Context) {
    // Read uploaded file
    file, header, err := c.Request.FormFile("file")
    if err != nil {
        c.JSON(utils.BuildError(err))
    }
    if file == nil {
        c.JSON(utils.BuildError(errors.New("no file provided")))
        return
    }

    // Get Client's informations ready to be processed
    var inputDTO InputDTO
    inputDTO.File = file
    inputDTO.Name = header.Filename
    c.JSON(utils.BuildResponse(inputDTO.addService()))
}

我使用这个 curl 请求对其进行了测试,它按预期工作:

curl -i -X POST -H "Content-Type: multipart/form-data" -F "file=@FILE.pdf" localhost:14000/api/v2/items

结果:

c.Request.Header => map[Content-Length:[787347] Expect:[100-continue] Content-Type:[multipart/form-data; boundary=------------------------b01a62679831e49b] User-Agent:[curl/7.46.0] Accept:[*/*]]

c.Request.Body => &{0xc0422a6000 0xc042280180 false false}

header => [some binary]

file => {0xc042080930}

现在,Photoshop javascript 只允许使用 Socket,所以我使用这个脚本:

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);
    content = "--" + boundary
        + "Content-Disposition: form-data; name=file; filename=" + filename + ".pdf\n"
        + "Content-Type: application/octet-stream\n"
        + "\n"
        + fContent;
        ;
    cs = "POST /api/v2/items HTTP/1.1\n"
        + "Content-Length: " + content.length + "\n"
        + "Content-Type: multipart/form-data; charset=utf-8; boundary=" + boundary + "\n"
        + "Host: 127.0.0.1:14000\n"
        + "User-Agent: Apache-HttpClient/4.3.1 (java 1.5)\n"
        + "Accept: */*\n"
        + "Expect: 100-continue\n"
        + "\n"
        + content
        + "--" + boundary + "--\n";

    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");
}

我收到了同样好的请求,但是 header 和 body 都没有...

c.Request.Header => map[User-Agent:[Apache-HttpClient/4.3.1 (java 1.5)] Accept:[*/*] Expect:[100-continue] Content-Length:[787299] Content-Type:[multipart/form-data; boundary=XLuvdG51D_BRiiAda_0y79ImMN_ddtKYzeFFLlu8]]

c.Request.Body => &{0xc042278380 0xc04204e2c0 false false}

header => nil

file => nil

知道为什么从 Socket 发送文件时文件为 nil 吗?

谢谢!

根本区别在于我试图发送 PDF,Content-Type 而不是 application/octet-stream 应该是 application/pdf 所以它不会误读 EOF文件中间。