I am trying to upload a file to my server (Golang) from a photoshop script (javascript)
Here is the service reading the file on the server:
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()))
}
I tested it using this curl request and it works as expected:
curl -i -X POST -H "Content-Type: multipart/form-data" -F "[email protected]" localhost:14000/api/v2/items
Result:
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}
Now, Photoshop javascript only allows the usage of Socket, so I use this script:
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");
}
And I get the same nice request, but header and body are nil...
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
Any idea of why the file is nil when sent from the Socket?
Thank you!
The fundamental difference was that I am trying to send a PDF, the Content-Type
instead of being application/octet-stream
was supposed to be application/pdf
so it doesn't misread EOF in the middle of the file.