gpt4 book ai didi

javascript - 上传多个AngularJS

转载 作者:行者123 更新时间:2023-12-02 16:08:56 26 4
gpt4 key购买 nike

我可以上传单个文件,但不能使用多个。我该怎么做?

这是我到目前为止尝试过的:

var myApp = angular.module('myApp', []);

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]);
console.log(element[0].files[0]);
});
});
}
};
}]);

myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl, callback){
var fd = new FormData();
var files = file;
fd.append('file', file);

$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(callback)
.error(callback);
}
}]);

myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file.name));

var uploadUrl = "http://httpbin.org/post";
fileUpload.uploadFileToUrl(file, uploadUrl,function(data, status, headers, config){
if(status == 200)console.log('Success!');
else console.log('Error!');
});
};

}]);

html:

<div ng-controller = "myCtrl">
<form>
<input type="file" multiple file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</form>

{{myFile.name}}
</div>

这里是jsfiddle:http://jsfiddle.net/ejx68/7/

最佳答案

您的代码有两个违背您意图的问题。

I fixed your Fiddle ,但会突出显示错误所在。

  1. 通过指令中的 for 循环,您将删除除最后选定的文件之外的所有文件。你根本不应该使用 for 循环,它们在那里毫无意义!只需传入文件数组即可。

    element.bind('change', function () {
    scope.$apply(function () {
    modelSetter(scope, element[0].files);
    });
    });
  2. 实际的上传函数仅处理单个文件,而它应该需要一个数组并上传所有项目。

    $scope.uploadFile = function () {
    var files = $scope.myFile,
    uploadUrl = "http://httpbin.org/post";

    function callback(data, status, headers, config) {
    if (status == 200) console.log('Success!');
    else console.log('Error!');
    }

    for (var i = 0; i < files.length; i++) {
    var file = files[i];
    console.log('file is ' + JSON.stringify(file.name));
    fileUpload.uploadFileToUrl(file, uploadUrl, callback);
    }
    };

    或者,如果您想在单个请求中上传所有文件,可以修改 uploadFileToUrl 将每个文件添加到 FormData。

关于javascript - 上传多个AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30438849/

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