how to upload file using Angularjs, multipart/form-data

后端 未结 2 1389
感动是毒
感动是毒 2020-12-20 10:07

i want to upload image using Angularjs anyone know how do this..REST API wants

Content-Type:multipart/form-data

www.abc.         


        
2条回答
  •  醉话见心
    2020-12-20 10:35

    Configure the headers with "Content-Type": undefined and use the FormData API:

      var config = { headers: {
                       "Content-Type": undefined,
                      }
                   };
    
      vm.upload = function() {
    
        var formData = new $window.FormData();
    
        formData.append("file-0", vm.files[0]);
    
        $http.post(url, formData, config).
         then(function(response) {
          vm.result = "SUCCESS";
        }).catch(function(response) {
          vm.result = "ERROR "+response.status;
        });
      };
    

    Normally the AngularJS $http service uses Content-Type: application/json. By setting Content-Type: undefined, the framework will omit the Content-Type header and the browser will use its default content type which is multipart/form-data for FormData objects.

    Request Header

    POST /post HTTP/1.1
    Host: httpbin.org
    Connection: keep-alive
    Content-Length: 388298
    Accept: application/json, text/plain, */*
    Origin: https://run.plnkr.co
    User-Agent: Mozilla/5.0 Chrome/55.0.2883.54 Safari/537.36
    Content-Type: multipart/form-data; boundary=----WebKitFormBoundary9lBDT4yoh8lKWtIH
    Referer: https://run.plnkr.co/cW228poRVzWs67bT/
    Accept-Encoding: gzip, deflate, br
    Accept-Language: en-US,en;q=0.8
    

    Request Payload

    ------WebKitFormBoundary9lBDT4yoh8lKWtIH
    Content-Disposition: form-data; name="file-0"; filename="Crop.jpg"
    Content-Type: image/jpeg
    
    
    ------WebKitFormBoundary9lBDT4yoh8lKWtIH--
    

    The DEMO on PLNKR.

    For more information see,

    • AngularJS $http Service API Reference -- Setting HTTP Headers

    • MDN Documents -- FormData API

提交回复
热议问题