Upload Angularjs Files

Asked

Viewed 3,779 times

0

I have a button where I select a file, I would like to upload that file to my server(Java + Vraptor). I can already get the file and also save the name of the file in the database along with the collaborator’s data. Now all that remains is to send this file to the server. I am using that model.

I upload it that way:

    $scope.uploadFiles = function(file) {
        $scope.f = file;

    }

    var salvarImagem = function(file) {
        if (file && !file.$error) {
            file.upload = Upload.upload({
                //Não sei o que colocar aqui!
                url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
                data: {
                    file: file
                }
            });

            file.upload.then(function(response) {
                $timeout(function() {
                    file.result = response.data;
                    console.log("REsposta: " + response.data);
                });
            }, function(response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            });

            file.upload.progress(function(evt) {
                file.progress = Math.min(100, parseInt(100.0 *
                    evt.loaded / evt.total));
            });
        }
    }

Then I call the function salvarImagem within my function that saves the Collaborator:

$scope.adicionarColaborador = function(colaborador) {
        if (!editar) {
            colaborador.arquivo = $scope.f.name;
            console.log('colaborador: ' + colaborador.arquivo)
            colaboradorAPI.saveColaborador(colaborador).success(function(data) {
            salvarImagem($scope.f);

         .../Código omitido

What’s the next step now? How to receive this image on my server and save it in a directory, or how to save this image to a direct directory?

  • 2

    I use this directive to upload multiple files simultaneously: https://github.com/danialfarid/ng-file-upload

1 answer

2


I’m starting to work with Angular now and I’ve just come across the need to upload directly to a server. I also used this ng-file-upload. I did it the same way as the example, just changing the url: 'https://angular-file-upload-cors-srv.appspot.com/upload' for the path to my server. For testing, I have uploaded a python server to receive this file. If I help you, follow the code snippets:

Javascript:

mainCtrl.controller('uploadCtrl', function ($scope, Upload, $timeout) {
$scope.uploadFiles = function(file, errFiles) {
    $scope.f = file;
    $scope.errFile = errFiles && errFiles[0];
    if (file) {
        file.upload = Upload.upload({
            url: 'http://192.168.1.112:5000/uploadImg',
            data: {file: file}
        });

        file.upload.then(function (response) {
            $timeout(function () {
                file.result = response.data;
                console.log("REsposta: " + 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));
        });
    }   
}
});

HTML:

<div ng-controller="uploadCtrl">
        <label>Selecione a imagem</label>
        <button type="file" ngf-select="uploadFiles($file, $invalidFiles)" accept="image/*" ngf-max-height="1000" ngf-max-size="1MB">Adicionar</button>
        <br><br>
        Arquivo:
        <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 + '%'"/>
            </span>
        </div>  
    </div>

Python:

app = flask.Flask(__name__)

@app.route('/uploadImg', methods=['POST', 'GET', 'OPTIONS'])
@crossdomain(origin="*")
def uploadImg():
    file = flask.request.files['file']
    filename = file.filename
    file.save('/tmp/'+ filename)
    return json.dumps('foo')

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.