简体   繁体   English

如何使用AngularJS上传文件?

[英]How to upload a file with AngularJS?

I am trying to upload a file with AngularJS. 我正在尝试使用AngularJS上传文件。 This is my code: 这是我的代码:

HTML HTML

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

JavaScript 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? 缺什么?

It looks like you're using code from this jfiddle for your app: 看起来你正在使用这个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(){
        });
    }
}]);

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. 你如何做到这一点取决于你的后端技术堆栈。

I had same issue. 我有同样的问题。 I tried following code and my problem was solved. 我尝试了下面的代码,我的问题解决了。

var req = {
    method: 'POST',
    url: url,
    headers: {
        'Content-Type': "application/json",
    },
    data: data,
    transformRequest: function(data, headersGetter) {
        var formData = new FormData();
        angular.forEach(data, function(value, key) {
            formData.append(key, value);
        });
        var headers = headersGetter();
        delete headers['Content-Type'];
        return formData;
    }
}

$http(req)
    .success(function(response) {
        $scope.Models = response;
    })
    .error(function(data, status, headers, config) {

        // called asynchronously if an error occurs
        // or server returns response with an error status.
        alert(data);
    });

 $scope.setFiles = function (element) { $scope.$apply(function (scope) { $scope.files = []; for (var i = 0; i < element.files.length; i++) { scope.files.push(element.files[i]) } }); }; $scope.uploadFile = function() { var fd = new FormData(); for (var i in $scope.files) { fd.append('file', $scope.files[i]) } $http.post('http://admin.localhost/images/patanjali', fd, { transformRequest: angular.identity, headers: { 'Content-Type': undefined } }) .then(function successCallback(response) { }, function errorCallback(response) { }); }; 
 <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js'></script> <input type="file" valid-file ng-model-instant id="fileToUpload" onchange="angular.element(this).scope().setFiles(this)" /> <button ng-click="uploadFile()">Upload me</button> 

You can use AngularJs modules for file uploader.The modules are very useful and very comfortable. 您可以将AngularJs模块用于文件上传器。这些模块非常实用且非常舒适。

1) https://github.com/nervgh/angular-file-upload 1) https://github.com/nervgh/angular-file-upload

2) https://github.com/danialfarid/ng-file-upload 2) https://github.com/danialfarid/ng-file-upload

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM