在AngularJS中,如果你在上传文件时遇到错误"当前请求不是多部分请求",这通常是因为你没有将请求标记为多部分请求。以下是解决此问题的代码示例:
HTML文件:
AngularJS控制器:
app.controller('myCtrl', function($scope, $http) {
$scope.uploadFile = function() {
var file = $scope.myFile;
var fd = new FormData();
fd.append('file', file);
$http.post('/upload', fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.then(function(response) {
// 处理上传成功的响应
})
.catch(function(error) {
// 处理上传失败的响应
});
};
});
在上面的代码示例中,我们创建了一个FormData对象,并将文件附加到其上。然后,我们使用$http.post
方法发送POST请求,将FormData对象作为请求体发送。我们还设置了Content-Type
标头为undefined
,并将transformRequest
设置为angular.identity
,以确保请求被标记为多部分请求。
请确保在服务器端正确处理多部分请求。这涉及到根据你的服务器框架和语言来处理上传的文件。