我正在尝试使用 AngularJS 上传文件。这是我的代码:
HTML
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
JavaScript
$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "http://admin.localhost/images/patanjali/";
VariantService.uploadFileToUrl(file, uploadUrl);
};
VariantService.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
alert ('success');
})
.error(function(){
});
}
虽然我可以在我的服务中看到(“成功”)警报,但该文件未保存在 Controller 中提供的位置。
有人可以帮助我吗?缺少什么?
最佳答案
您似乎正在使用 code from this jfiddle对于您的应用程序:
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
如果配置正确,这仅用于从客户端发布数据;服务器还需要配置为接受/保存数据。如何执行此操作取决于您的后端技术堆栈。
关于javascript - 如何使用 AngularJS 上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31077947/