Build multipart/form-data POST request in Angular2 and validate Input type File

后端 未结 3 1293
遇见更好的自我
遇见更好的自我 2020-12-19 06:21

I have an image (base64) that I need to send via a POST request (and wait for the response). The POST request needs to be of Content-Type:multipart/form-data.

3条回答
  •  清酒与你
    2020-12-19 06:40

    Similar to this question here: Angular 2 - Post File to Web API

    Angular2 does not yet support multipart/form-data POST requests, so I decided to use jQuery instead to implement it, and then convert it to an RxJs Observable (subject) to have the same type as what the http.post function in Angular2 should have:

    //Convert Base64 Representation of jpeg to 
    let imageData = imageString.split(',')[1];
    let dataType = imageString.split('.')[0].split(';')[0].split(':')[1];
    let binaryImageData = atob(imageData);
    let data = new FormData();
    let blob = new Blob([binaryImageData], { type: dataType })
    data.append('file', blob);
    let deferred = $.ajax({
      url: this._imageAPIBaseUrl,
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      type: 'POST'
    });
    let observable = new AsyncSubject();
    
    //When the Deferred is complete, push an item through the Observable
    deferred.done(function () {
    
      //Get the arguments as an array
      let args = Array.prototype.slice.call(arguments);
    
      //Call the observable next with the same parameters
      observable.next.apply(observable, args);
    
      //Complete the Observable to indicate that there are no more items.
      observable.complete();
    });
    
    //If the Deferred errors, push an error through the Observable
    deferred.fail(function () {
    
      //Get the arguments as an array
      let args = Array.prototype.slice.call(arguments);
    
      //Call the observable error with the args array
      observable.error.apply(observable, args);
      observable.complete();
    });
    
    return observable;
    

提交回复
热议问题