我必须使用rest api上传图片才能成功上传将获得文件夹目标ex:D:/ddd/download
的响应,我无法上传图片,下面是我给出的代码建议我进行任何更正。上传图片时我必须将参数名称作为fileData。
api ex:http://somelink和post的参数是fileData
Html代码
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
我的服务和指示
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
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(){
});
}
}]);
我的控制器文件
$scope.uploadFile = function(){
var data={
'fileData':$scope.myFile
}
var uploadUrl = "http://";
fileUpload.uploadFileToUrl(data, uploadUrl).success(function(response) {
$scope.fileName=response;
})
};
答案 0 :(得分:0)
请检查一下...... 控制器:
$scope.uploadFile = function () {
var file = $scope.myFile;
console.log(file);
if(file.type==='image/jpeg' || file.type==='image/jpg' || file.type==='image/png' ){
var uploadUrl = "http://";
fileUpload.uploadFileToUrl(file, uploadUrl);
angular.element('input[type="file"]').val(null);
}else{
$scope.errorMessage='File Type Error';
}
};
服务:
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, url) {
var uploadUrl = url;
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function () {
console.log("Image Save");
})
.error(function () {
});
};
}]);
答案 1 :(得分:0)
您希望将文件本身传递给formdata对象
fileUpload.uploadFileToUrl($scope.myFile, uploadUrl).success(function(response) {
$scope.fileName=response;
})
并将append的第一个参数设置为fileData
fd.append('fileData', file);
答案 2 :(得分:0)
嗨朋友们现在图片上传工作正常,我已经删除了服务并通过添加以下代码对我的控制器进行了更改。
var file = $scope.myFile;
var uploadUrl = "http://";
var fd = new FormData();
fd.append('fileData', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(response){
$rootScope.fileValue = response;
})