如何使用Angularjs,multipart / form-data上传文件

时间:2016-11-29 14:32:53

标签: javascript angularjs angularjs-directive angularjs-scope

我想使用Angularjs上传图片,任何人都知道如何...REST API想要

  

内容类型:多部分/格式数据

www.abc.com/images/id
Request Body
{
    // --Boundary_1_1626119499_1392398808202
    // Content-Type: image/png
    // Content-Disposition: form-data; filename="ducky.png"; modification-date="Wed, 05 Nov 2016 19:53:17 GMT"; size=713915; name="upload_image"        

    // {binary data truncated for display}
}

我的问题是如何使用上面的rest API上传图像文件,如何分配$ scope.tempObject = my上传图片路径

 $scope.UploadImage =  function () { 
        var config = {headers:  {      
    'Content-Type': 'multipart/form-data'

       }
        }

    $http.post(properties.customerUploadImage_path + "/"+checkprofile,$scope.tempObject,config).success(function (response) { 
 Console.log('Uploaded');
    });


    } 

2 个答案:

答案 0 :(得分:1)

我认为你没有以正确的方式使用$http

您可以使用headers服务的$http属性,如下所示:

$scope.UploadImage = function () { 
  var config = {
    headers: {      
      'Content-Type': 'multipart/form-data',
    }
  };

  $http({
    method: 'POST',
    url: properties.customerUploadImage_path + "/" + checkprofile,
    data: $scope.tempObject,
    config: config,
  }).success(function (response) { 
    console.log('Uploaded');
  });


};

我建议你看看documentation

答案 1 :(得分:1)

使用"Content-Type": undefined配置标头并使用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;
    });
  };

通常,AngularJS $ http服务使用Content-Type: application/json。通过设置Content-Type: undefined,框架将省略Content-Type标头,浏览器将使用其默认内容类型multipart/form-data用于FormData对象。

请求标题

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

请求有效负载

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


------WebKitFormBoundary9lBDT4yoh8lKWtIH--

DEMO on PLNKR

有关详细信息,请参阅