gpt4 book ai didi

javascript - 在Angularjs中使用rest api上传图像

转载 作者:行者123 更新时间:2023-12-02 18:50:53 25 4
gpt4 key购买 nike

我必须使用rest api上传图像才能成功上传,将获得文件夹目标的响应,例如:D:/ddd/download,我无法上传图像,下面是我的代码给我建议任何更正。上传图像时,我必须将参数名称指定为 fileData。API 示例: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(){
});
}
}]);

我的 Controller 文件

 $scope.uploadFile = function(){
var data={
'fileData':$scope.myFile
}
var uploadUrl = "http://";
fileUpload.uploadFileToUrl(data, uploadUrl).success(function(response) {
$scope.fileName=response;
})
};

最佳答案

请检查一下... Controller :

   $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 () {
});
};

}]);

关于javascript - 在Angularjs中使用rest api上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39887829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com