[英]Posting file through angular http request
我正在使用angularjs,我正在尝试将图片与请求正文中的其他数据一起上传到django后端服务器。
我一直收到来自服务器的错误,告诉我我发送的图片不是文件。 (假设后端没有问题)
我尝试使用ng-file-upload( https://github.com/danialfarid/ng-file-upload )来获取文件,然后通过angular本身发送它。 (注意:我需要将其他数据与图片一起发送)所以我想将文件存储在变量中并将其传递到请求体中,如下所示:
<form name="form">
<div class="button" ngf-select ng-model="file" name="file" ngf-resize="{width: 100, height: 100}">Select</div>
<button type="submit" ng-click="submit()">submit</button>
</form>
由于文件存储在$ scope.file中,我尝试在http请求中使用它:
$http({
'method': "PUT",
'url': "api/candidate-profiles/" + id,
'data':data
})
数据是:
{"id": $scope.id,
"name": $scope.name,
"avatar":$scope.file}
我从后端收到验证错误,指出该头像不是文件。 有帮助吗?
HTML
<div ng-controller="formCtrl">
<form name="userForm" class="well form-search" >
<input type="text" ng-model="name" class="input-medium search-query" placeholder="Name" required >
<input type="email" ng-model="email" class="input-medium search-query" placeholder="Email" required >
<input type="text" ng-model="message" class="input-medium search-query" placeholder="Message" required >
<button type="submit" class="btn" ng-click="formsubmit(userForm.$valid)" ng-disabled="userForm.$invalid">Submit </button>
</form>
<pre ng-model="result">
{{result}}
</pre>
</div>
jsfile
var app = angular.module('formExample', []);
app.controller("formCtrl", ['$scope', '$http', function($scope, $http) {
$scope.url = 'submit.php';
$scope.formsubmit = function(isValid) {
if (isValid) {
$http.post($scope.url, {"name": $scope.name, "email": $scope.email, "message": $scope.message}).
success(function(data, status) {
console.log(data);
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
})
}else{
alert('Form is not valid');
}
} }]);
我想你应该阅读文档,并看到像一些样品本
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadPic = function(file) {
file.upload = Upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
data: {username: $scope.username, file: file},
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.