0

我想用Angularjs上传图片谁知道this..REST API希望如何使用Angularjs,多/表单数据

的Content-Type怎么做才能上传文件:多/ 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 =我上传图片的路径

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


    } 
+0

使用的Content-type:未定义 –

+1

嗨,你应该考虑使用这个库。它真的为我做了伎俩:) https://github.com/danialfarid/ng-file-upload – Deunz

回答

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

配置与"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

欲了解更多信息,请参阅

相关问题