Posting multipart/form-data using AS3

Une petite class AS3 pour générer des requêtes POST contenant des données en multipart forma-data.

Je me suis d’abord basé sur la RFC 1867, puis sur l’observation des requête générées par les form html qui était sensiblement différentes, notamment sur la gestion de multiples champs textes en POST…

La démo
Les sources

Utilisation :

var form:Multipart = new Multipart(url);
 
// add fields
form.addField("field1", "hello");
form.addField("field2", "world");
 
// create txt files
var txt:ByteArray = new ByteArray();
txt.writeMultiByte("Hello", "ascii");
 
// create jpg file from bitmapData
// http://www.bytearray.org/?p=775
var enc:JPEGEncoder = new JPEGEncoder(80);
var jpg = enc.encode(bitmapData);
 
// add files
form.addFile("file1", txt, "text/plain", "test.txt", true);
form.addFile("file2", jpg, "application/octet-stream", "test.jpg", true);
 
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onComplete);
loader.load(form.request);

9 thoughts on “Posting multipart/form-data using AS3

  1. Thanks very much!!!! Great job. After two days with other solutions on web I found this and IT SAVE MY DAY!

    • Hello. I’ve found an error in your code.
      After some web search I’ve found that the content-type should be defined like this:
      var r: URLRequest = new URLRequest(_url);
      //r.contentType = “multipart/form-data; boundary=” + boundary; where is the problem!
      r.requestHeaders.push(new URLRequestHeader(‘Content-type’, ‘multipart/form-data; boundary=’ + boundary)); // this is the correct way to set content-type
      r.data = _data;
      r.method = URLRequestMethod.POST;
      return r;

      Dispite this, great work.

      Best regards,
      Tiago Ribeiro.

Leave a Reply

Your email address will not be published. Required fields are marked *