且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-03-31 07:40:39

使用 "Content-Type": undefined 配置标题并使用 FormData API:

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;
    });
  };

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

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.

请求标头

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--

PLNKR 演示.

有关详细信息,请参阅

MDN 文档 -- FormData API