Last Updated: February 25, 2016
·
881
· minodisk

FormData in ActionScript

package {
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;

public class FormData {
  static private const CHARS:String = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

  static private function createRandom(length:int):String {
    var len:int, str:String;
    len = CHARS.length;
    str = '';
    while (str.length < length) {
      str += CHARS.charAt(Math.random() * len >> 0);
    }
    return str;
  }

  private var _data:Array;
  private var _boundary:String;

  public function FormData() {
    _data = [];
    _boundary = '----FlashFormDataBoundary' + createRandom(16);
  }

  public function append(name:String, value:*, filename:String = null, contentType:String = 'image/png'):void {
    _data.push({
      name       : name,
      value      : value,
      filename   : filename,
      contentType: contentType
    });
  }

  public function apply(req:URLRequest):void {
    var bytes:ByteArray = new ByteArray();
    _bound(bytes);
    for (var i:int, len:int = _data.length, data:Object; i < len; i++) {
      data = _data[i];
      bytes.writeUTFBytes('Content-Disposition: form-data; name="' + data.name + '"');
      if (data.filename) {
        bytes.writeUTFBytes('; filename="' + data.filename + '"\r\n');
        bytes.writeUTFBytes('ContentType: ' + data.contentType);
      }
      bytes.writeUTFBytes('\r\n\r\n');
      if (data.value is ByteArray) {
        bytes.writeBytes(data.value);
      } else {
        bytes.writeUTFBytes(data.value);
      }
      bytes.writeUTFBytes('\r\n');
      _bound(bytes, i === len - 1);
    }

    req.method = URLRequestMethod.POST;
    req.data = bytes;
    req.contentType = 'multipart/form-data; boundary=' + _boundary;
  }

  private function _bound(bytes:ByteArray, end:Boolean = false):void {
    bytes.writeUTFBytes('--' + _boundary + (end ? '--' : '\r\n'));
  }
}
}