You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS文件上传报错TypeError: Cannot read properties of undefined (reading 'uploadFileToUrl')求助

AngularJS文件上传报错TypeError: Cannot read properties of undefined (reading 'uploadFileToUrl')求助

看起来你遇到的这个报错是因为AngularJS依赖注入的顺序不匹配导致的,我帮你分析下问题所在:

核心问题:依赖注入顺序错误

你的CsvController依赖数组里声明的是['$scope', 'fileUpload'],但对应的函数参数却写成了function($scope,$http, fileUpload)——多了一个$http参数!这会让AngularJS按顺序匹配依赖:第一个参数$scope对应正确,第二个参数$http会被注入原本应该给fileUpload的服务,第三个参数fileUpload就变成了undefined,自然调用uploadFileToUrl时就会抛出你看到的错误。

修正后的控制器代码

把控制器里的参数顺序调整成和依赖数组一致,去掉多余的$http参数即可:

app.controller('CsvController', ['$scope', 'fileUpload', function($scope, fileUpload){
    $scope.uploadFile = function(){
        var file = $scope.myFile;
        console.log('file is ' );
        console.dir(file);
        var REST_BASE_URL = PluginHelper.getPluginRestUrl("apponboarding");
        console.log('BASE URL is ' );
        console.log(REST_BASE_URL);
        var uploadUrl = REST_BASE_URL+ "/upload";
        console.log('uploadUrl URL is ' );
        console.log(uploadUrl);
        console.log(fileUpload);
        fileUpload.uploadFileToUrl(file, uploadUrl);
        console.log("Controller END");
    };
}]);

额外检查点

除了依赖注入的问题,你还可以确认以下几点确保上传流程正常:

  • 确认fileModel指令能正确获取选中的文件:点击上传前可以先在控制台打印$scope.myFile,确保它不是undefined
  • 验证后端接口路径:检查PluginHelper.getPluginRestUrl("apponboarding")返回的URL是否正确,确保uploadUrl和Java后端的@PostMapping("/upload")路径完全匹配(注意上下文路径是否一致)
  • 后端文件接收逻辑:你的Java代码里使用了uploads/目录,要确保这个目录在服务器上存在且有读写权限,避免文件保存时抛出IO异常

附你提供的相关代码参考:

前端页面代码(Mypage.xhtml)

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>CSV Upload</title>
    <script src="#{plugins.requestContextPath}/plugin/apponboarding/ui/js/jquery.min.js" />
    <script src="#{plugins.requestContextPath}/plugin/apponboarding/ui/js/angular.min.js"></script>
    <script src="#{plugins.requestContextPath}/plugin/apponboarding/ui/js/apponboardingModule.js"></script>
    <script src="#{plugins.requestContextPath}/plugin/apponboarding/ui/js/bootstrap.min.js" />
</head>
<body ng-app="csvApp" ng-controller="CsvController">
    <h1>Upload CSV File</h1>
    <input type="file" file-model="myFile"/>
    <button type="button" ng-click="uploadFile()">Upload</button>

<script>
// app.js
var app = angular.module('csvApp', []);

app.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]);
                });
            });
        }
    };
}]);

app.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        console.log("inside service");
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
        })
        .then(function(response){
            console.log("File uploaded successfully");
        }, function(error){
            console.log("Error uploading file");
        });
    }
}]);

// 注意:这里是原代码中出错的部分,已在上方给出修正版
app.controller('CsvController', ['$scope', 'fileUpload', function($scope,$http, fileUpload){
    $scope.uploadFile = function(){
        var file = $scope.myFile;
        console.log('file is ' );
        console.dir(file);
        var REST_BASE_URL = PluginHelper.getPluginRestUrl("apponboarding");
        console.log('BASE URL is ' );
        console.log(REST_BASE_URL);
        var uploadUrl = REST_BASE_URL+ "/upload";
        console.log('uploadUrl URL is ' );
        console.log(uploadUrl);
        console.log(fileUpload);
        fileUpload.uploadFileToUrl(file, uploadUrl);
        console.log("Controller END");
    };
}]);
</script>
</body>
</html>

报错信息

TypeError: Cannot read properties of undefined (reading 'uploadFileToUrl')
    at $scope.uploadFile (pluginPage.jsf?pn=apponboarding:1511:20)
    at fn (eval at compile (angular.min.js:239:266), <anonymous>:4:150)
    at e (angular.min.js:284:187)
    at b.$eval (angular.min.js:148:347)
    at b.$apply (angular.min.js:149:52)
    at HTMLButtonElement.<anonymous> (angular.min.js:284:239)
    at HTMLButtonElement.dispatch (jquery.min.js:3:10316)
    at q.handle (jquery.min.js:3:8343)

后端Java代码

@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
        log.error("New Function- Empty File Detected-");
        return new ResponseEntity<>("No file uploaded.", HttpStatus.BAD_REQUEST);
    }

    try {
        // Save the file to the server
        log.error("New Function- File Detected-");
        String uploadDir = "uploads/";
        File uploadFile = new File(uploadDir + file.getOriginalFilename());
        file.transferTo(uploadFile);

        return new ResponseEntity<>("File uploaded successfully.", HttpStatus.OK);
    } catch (IOException e) {
        return new ResponseEntity<>("Error uploading file.", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

备注:内容来源于stack exchange,提问作者Aditya Bhatnagar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 09:34:28