Copy link to clipboard
Copied
I´m trying to download an image from an URL with Javascript using socket.
My first problem was separating the header from the body. I do it by reading line by line and if the line starts with "\n" then it seams to be the body.
A problem with this is that it´s very very slow. Reading a 1x1 pixel png takes 5-10 seconds.
The stranger thing is that I can´t write the content to file. I can write a string to a file, but not the body of the image, toString() doesn´t seem to help.
Anyone with experience or advice?
var img_data = "";
var line;
var body_start = false;
var conn = new Socket;
if (conn.open ("www.test.com:80", "BINARY")) {
var request = "GET /phoenix/images/5_topnavlogo.jpg HTTP/1.1\n" +
"Host: www.test.com\n" +
"User-Agent: InDesign ExtendScript\n" +
"Accept: text/xml,text/*,*/*\n" +
"Accept-Encoding:\n" +
"Content-Length: 0\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Connection: keep-alive\n" +
"Accept-Language: *\n" +
"Accept-Charset: utf-8\n" +
"\n";
conn.write(request);
while(!conn.eof) {
line = conn.readln(255);
if(line.substring(0, 1) == "\n") {
img_data = line.substring(1);
}
}
conn.close();
alert(img_data);
var img_file = new File(File(app.activeScript).parent + '/test.txt');
img_file.open('w');
img_file.write(img_data);
img_file.close();
alert("Done");
}
I got my code working. I changed one line from:
socket.open(host + ":80")to
socket.open(host + ":80", "BINARY")
Copy link to clipboard
Copied
http://rorohiko.blogspot.com/2008_07_01_archive.html
demonstrates how to do the basics of what you need.
Cheers,
Kris
Copy link to clipboard
Copied
Did you figure out why the image wasn't writing? I have the same issue. The jpg response won't write to the file properly. When I try to open the image file that was created by the script I get:
The file “newImg.jpg” could not be opened.
It may be damaged or use a file format that Preview doesn’t recognize.
var host = "www.myhost.com";
var url = "/this.jpg";
var f = File("/imgs/temp/newImg" + url.substr(url.length - 4)); // 4 = .gif or .jpg
f.open("w");
f.encoding = "BINARY";
var socket = new Socket;
if (socket.open(host + ":80")) {
socket.timeout = 16000;
app.consoleout("Connected!");
socket.write("GET " + url + " HTTP/1.0\r\nHost:" + host + "\r\nConnection: close\r\n\r\n");
var binary = socket.read(9999999);
binary = removeHeaders(binary);
f.write(binary); // image won't open so this isn't working right
socket.close();
}
f.close();
//f.remove(); // Remove temporary downloaded files
Copy link to clipboard
Copied
I got my code working. I changed one line from:
socket.open(host + ":80")to
socket.open(host + ":80", "BINARY")
Get ready! An upgraded Adobe Community experience is coming in January.
Learn more