I've got a REST api which assumes a multipartfile in the a post method.
Is there any way to do this kind of posts in Dart / AngularDart because all the solutions I've found so far are not working.
I've tried to use the http://dart-gde.github.io/dart-google-oauth2-library/multipart_file/MultipartFile.html solution, but it is not working in the browser because dart.io is not supported there.
My question is about the client side part directly from the browser. The serverside, which is written in Java can handle the post.
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.
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"/>