如何使用Angularjs,multipart / form-data上传文件 [英] how to upload file using Angularjs, multipart/form-data

查看:342
本文介绍了如何使用Angularjs,multipart / form-data上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Angularjs上传图片任何人都知道怎么做这个..REST API想要

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


Content-Type:multipart / form-数据

Content-Type:multipart/form-data



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

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

my Question is how to upload image file using above rest API, how to assign $scope.tempObject = my Upload image Path

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


    } 


推荐答案

使用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标头,浏览器将使用其默认内容类型 multipart / form --Data for FormData对象。

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上的DEMO

有关详细信息,请参阅,

For more information see,

MDN文档 - FormData API

这篇关于如何使用Angularjs,multipart / form-data上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆