简体   繁体   中英

Upload file angular

I have a simple form

<div ng-controller='MyCtrl'>
 <form ng-submit='submit()'>
    <input name="name" value="name">
    <lf-ng-md-file-input lf-files='files'> </lf-ng-md-file-input>
    <button type='submit'> Submit
 </form>
</div>

I use this html element for choosing file on client side: https://github.com/shuyu/angular-material-fileinput .

How can I access to my upload file to send it on server?

I'd recommend using Ng-File-upload Will do the trick you can do something like this, there is more documentation on the site as well as the fiddle for different examples

<body ng-app="fileUpload" ng-controller="MyCtrl">
 <h4>Upload on file select</h4>
  <button type="file" ngf-select="uploadFiles($file, $invalidFiles)"
      accept="image/*" ngf-max-height="1000" ngf-max-size="1MB">
  Select File</button>
  <br><br>
  File:
  <div style="font:smaller">{{f.name}} {{errFile.name}} {{errFile.$error}} {{errFile.$errorParam}}
  <span class="progress" ng-show="f.progress >= 0">
      <div style="width:{{f.progress}}%"  
           ng-bind="f.progress + '%'"></div>
  </span>
 </div>     
  {{errorMsg}}
</body>

Controller:

//inject angular file upload directives and services.
var app = angular.module('fileUpload', ['ngFileUpload']);

app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
    $scope.uploadFiles = function(file, errFiles) {
    $scope.f = file;
    $scope.errFile = errFiles && errFiles[0];
    if (file) {
        file.upload = Upload.upload({
            url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
            data: {file: file}
        });

        file.upload.then(function (response) {
            $timeout(function () {
                file.result = response.data;
            });
        }, function (response) {
            if (response.status > 0)
                $scope.errorMsg = response.status + ': ' + response.data;
        }, function (evt) {
            file.progress = Math.min(100, parseInt(100.0 * 
                                     evt.loaded / evt.total));
        });
    }   
  }
}]);

Hi ~ sorry i not illustrate the lf-ng-md-file-input clearly.

This angular directive is focus on make material look and upload file base on ajax.

So the most important thing is you need fetch files yourself from "lf-files" data bind, not input element because it clear every time after resolve file.

The "lf-files" data is an array variable, object in array contain properties with lfFileName(file name) 、 lfFile(file object) and lfDataUrl(for preview) from resolve input file.

You can observe "lf-files" by using $watch.

html :

<lf-ng-md-file-input lf-files='files' multiple> </lf-ng-md-file-input>

javascript :

app.controller('MyCtrl',function($scope){
    $scope.$watch('files.length',function(newVal,oldVal){
        console.log($scope.files);
    });
});

So after you finish select files you need adjust data like below to fit your server side.

javascript :

app.controller('MyCtrl',function($scope){

    ...

    $scope.onSubmit = function(){
        var formData = new FormData();
        angular.forEach($scope.files,function(obj){
            formData.append('files[]', obj.lfFile);
        });
        $http.post('./upload', formData, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).then(function(result){
            // do sometingh                   
        },function(err){
            // do sometingh
        });
    };

    ...

});

In my case i use node.js( express + formidable ) on server side, "Formidable" is a node module for parsing form data, there has other similar like "Multer".

Server :

var express = require('express');
var formidable = require('formidable');
var app = express();
app.use(express.static(__dirname + '/public'));

...

app.post('/upload',function(req,res){
    var form = new formidable.IncomingForm();
    form.uploadDir = __dirname +'/public/uploads';
    //file upload path
    form.parse(req, function(err, fields, files) {
        //you can get fields here
    });
    form.on ('fileBegin', function(name, file){
        file.path = form.uploadDir + "/" + file.name;
        //modify file path
    });
    form.on ('end', function(){
        res.sendStatus(200);
        //when finish all process    
    });
});

...

I hope this will help .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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