Dev*_*wal 20 javascript file-upload angularjs
我正在尝试使用AngularJS上传文件.这是我的代码:
HTML
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
Run Code Online (Sandbox Code Playgroud)
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(){
});
}
Run Code Online (Sandbox Code Playgroud)
虽然我可以在我的服务中看到("成功")警报,但该文件未保存在控制器中提供的位置.
有人能帮我吗?缺什么?
小智 13
看起来你正在使用这个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(){
});
}
}]);
Run Code Online (Sandbox Code Playgroud)
正确配置后,这仅用于从客户端发布数据; 服务器还需要配置为接受/保存数据.你如何做到这一点取决于你的后端技术堆栈.
我有同样的问题.我尝试了下面的代码,我的问题解决了.
var req = {
method: 'POST',
url: url,
headers: {
'Content-Type': "application/json",
},
data: data,
transformRequest: function(data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function(value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
}
$http(req)
.success(function(response) {
$scope.Models = response;
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert(data);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4637 次 |
| 最近记录: |