javascript - 如何使用 AngularJS 上传文件?

标签 javascript angularjs file-upload

我正在尝试使用 AngularJS 上传文件。这是我的代码:

HTML

<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>

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

虽然我可以在我的服务中看到(“成功”)警报,但该文件未保存在 Controller 中提供的位置。

有人可以帮助我吗?缺少什么?

最佳答案

您似乎正在使用 code from this 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(){
        });
    }
}]);

如果配置正确,这仅用于从客户端发布数据;服务器还需要配置为接受/保存数据。如何执行此操作取决于您的后端技术堆栈。

关于javascript - 如何使用 AngularJS 上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31077947/

相关文章:

jquery - 添加条纹表格样式,包括悬停功能

javascript - 如果结果是 Angularjs 1.5 中的填充数组,则重复 $http.get 请求

javascript - jQuery 选择器只选择 php 循环结果末尾的最后一个 id

javascript - AWS S3 访问仅有时被拒绝

javascript - 延迟加载和依赖解析

javascript - 使用 JavaScript/jQuery 临时启用/禁用 "click sound"

javascript - babel 装饰器和 TypeScript 的一样吗?

angularjs - 使用 ui-router 在加载时将服务的数据放入嵌套 View

php - Slim PHP 上传目标路径不可写

javascript - 为什么在应用类时需要 setTimeout 才能让我的过渡生效?