POST requests in JS

Anyone, especially newbies, asking for help with Photoshop Scripting and Photoshop Automation - as opposed to those contributing to discussion about an aspect of Photoshop Scripting

Moderators: Tom, Kukurykus

dieki_n

POST requests in JS

Post by dieki_n »

I'm trying to write an Imgur upload script in Javascript. I've got it all working up until actually uploading to the server.

Imgur requires a POST request with the API key and the image data. (Binary or encoded as base64) Having read bb/viewtopic.php?f=15&t=3184, I've adapted the example from that thread to successfully send a post request (See code below), but something must be wrong, 'cause I just keep getting a 400 error from Imgur.

So; is there a simpler, more abstracted way to send POST requests? Or, if not, how can I send POST requests with file data via Socket?

Code: Select all  var socket = new Socket;
    boundary = "----------------------------8ce5b9c98602903";
   if (socket.open("api.imgur.com:80", "binary")){
        key = <my imgur api key>;
        socket.writeln("POST http://api.imgur.com/2/upload.json HTTP/1.0");
        socket.writeln("Content-Type: multipart/form-data; boundary=" + boundary);
        socket.writeln("Content-Length: " + (data.length + key.length));
        socket.writeln("Connection: close");
        socket.writeln();
        socket.writeln(boundary);
        socket.writeln("Content-Disposition: form-data; name='key'");
       
        socket.writeln();
        socket.writeln(key);
        socket.writeln(boundary);
       
        socket.writeln("Content-Disposition: form-data; name='image'");
        socket.writeln("Content-Type: image/jpeg");
        socket.writeln();
        socket.writeln(data);
        socket.writeln(boundary);

        alert("Sent!");
       
        var result = socket.read(9999999);
        alert(result);
        socket.close();
    }