How can I do a multipart Post in Dart / AngularDart

痴心易碎 提交于 2019-12-01 01:12:38

If you need multipart for file upload, all you have to do is send a FormData object using the HttpRequest class. Example:

import "dart:html";

...

var fileData; //file data to be uploaded

var formData = new FormData();
formData.append("field", "value"); //normal form field
formData.appendBlob("data", fileData); //binary data

HttpRequest.request("/service-url", method: "POST", sendData: formData).then((req) {
  ...
});

Furthermore, if you need to allow the user to upload a file from his hard disk, you have to use a html form with an <input type="file"> tag. Example:

Html file:

<form id="myForm" action="/service-url" method="POST" enctype="multipart/form-data">
  <input type="text" name="field"> <!-- normal field -->
  <input type="file" name="fileData"> <!-- file field -->
</form>

dart file:

var formData = new FormData(querySelector("#myForm"));
HttpRequest.request("/service-url", method: "POST", sendData: formData).then((req) {
  ...
});

I know this was asked a long time ago, but I've just had the same problem and the fix for me is the following (based on luizmineo's answer):

  • Use formData.appendBlob("data", fileData);
  • Don't set an explicit Content-Type header. This will get Dart to calculate the boundary section of the form-data which is crucial.
Zied Hamdi

I finally found a way to post it as a multi-part form:

void uploadFiles() {
    var formData = new FormData(querySelector("#fileForm"));
    HttpRequest.request("/sp/file", method: "POST", sendData: formData).then((req) {
        print("OK");
    });
}

is used in conjunction with

<form id="fileForm" action="/sp/file" method="POST">
    <input type="file" #upload (change)="uploadFiles(upload.files)"
             (dragenter)="upload.style.setProperty('border', '3px solid green')"
             (drop)="upload.style.setProperty('border', '2px dotted gray')" class="uploadDropZone" name="toUpload"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!