如何使用AngularJS上传文件? [英] How to upload a file with AngularJS?

查看:471
本文介绍了如何使用AngularJS上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to upload a file with AngularJS. This is my code:

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

尽管我可以在服务中看到(成功")警报,但文件未保存在控制器中提供的位置.

Although I can see the ('success') alert in my service, the file is not saving in the location provided in controller.

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

Can someone help me? What is missing?

推荐答案

您似乎正在使用此jfiddle中的代码用于您的应用程序:

It looks like you're using code from this jfiddle for your app:

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

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

While properly configured, this is only for posting data from the client side; the server also needs to be configured to accept/save the data. How you do this depends on your back-end tech stack.

这篇关于如何使用AngularJS上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆