I’m trying to figure out how to use sockets to upload to my web space. What I have so far is based primarily on Lee Brimelow’s Binary Socket Fundamentals tutorial. Currently, I can successfully establish a connection to the server, change the transfer type and switch to passive mode (I don’t know if I’m doing these correctly, or if they’re even necessary - I was basically mimicking the commands output by FileZilla when I log in and upload a file). I can even get the file to appear in the online destination directory, but the name is either non-existent or completely cryptic. I was wondering if anybody could tell me what I’m doing wrong or what I should be doing to actually get the file (fileToUpload) online and named properly? Also, how might I go about tracking the progress (bytes loaded / total bytes) as it uploads?
package com.jiggzy.ftpSocketTest {
import flash.net.Socket;
import flash.events.ProgressEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
public class FileUploader {
private var socket:Socket;
private var fileToUpload:File;
public function FileUploader(fileToUpload:File) {
this.fileToUpload = fileToUpload;
uploadFile();
}
private function uploadFile():void {
socket = new Socket("jiggzy.com", 21);
socket.addEventListener(ProgressEvent.SOCKET_DATA, socketProgress);
}
private function socketProgress(event:ProgressEvent):void {
var serverResponseFull:String = socket.readUTFBytes(socket.bytesAvailable);
var serverResponse:Number = Number(serverResponseFull.substr(0, 3));
trace("serverResponse: " + serverResponseFull);
if (serverResponse == 220) { //220 DreamHost FTP
socket.writeUTFBytes("USER myUsername
");
socket.flush();
} else if (serverResponse == 331) { //331 Password required for myUsername
socket.writeUTFBytes("PASS myPassword
");
socket.flush();
} else if (serverResponse == 230) { //230 User myUsername logged in
socket.writeUTFBytes("CWD jiggzy.com/tempdirectory
");
socket.flush();
} else if (serverResponse == 250) { //250 CWD command successful
socket.writeUTFBytes("Type A
");
socket.flush();
} else if (serverResponse == 200) { //200 Type set to A
socket.writeUTFBytes("PASV
");
socket.flush();
} else if (serverResponse == 227) { //227 Entering Passive Mode
var fileStream:FileStream = new FileStream();
fileStream.open(fileToUpload, FileMode.READ);
var fileContents:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
socket.writeUTFBytes("STOR " + fileContents + "
");
socket.flush();
}
}
}
}