How can I do a multipart Post in Dart / AngularDart

前端 未结 3 1889
小鲜肉
小鲜肉 2021-01-07 11:58

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\

相关标签:
3条回答
  • 2021-01-07 12:03

    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"/>
    
    0 讨论(0)
  • 2021-01-07 12:05

    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.
    0 讨论(0)
  • 2021-01-07 12:24

    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) {
      ...
    });
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题