Last active
March 30, 2016 04:19
-
-
Save lricoy/733654ee4cc62d4e100c06657e85209a to your computer and use it in GitHub Desktop.
Formulário para upload direto para o S3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html ng-app="myApp"> | |
<head> | |
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.min.js"></script> | |
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/danialfarid-angular-file-upload/12.0.4/ng-file-upload-all.js"></script> | |
</head> | |
<body> | |
<h1>S3 Direct Upload</h1> | |
<hr /> | |
<form ng-controller="MyCtrl" name="form"> | |
<input type="file" | |
ngf-select | |
ng-model="file" | |
name="file" | |
accept="*" ngf-max-size="10MB" required | |
> | |
<button type="submit" ng-click="submit()">Realizar upload </button> | |
<hr> | |
<span class="progress" ng-show="progress > 0"> | |
<div style="width:{{progress}}%" ng-bind="progress + '%'" class="ng-binding"></div> | |
</span> | |
<span ng-show="progress === 100"> | |
<a ng-href="{{s3Url}}">URL NO S3 - {{s3Url}}</a> | |
</span> | |
</form> | |
<script type="text/javascript"> | |
var app = angular.module('myApp', ['ngFileUpload']); | |
app.controller('MyCtrl', ['$scope', 'Upload', '$http', function ($scope, Upload, $http) { | |
// Método que trata o evento do formulário | |
$scope.submit = function() { | |
if ($scope.form.file.$valid && $scope.file) { | |
$scope.upload($scope.file); | |
} | |
}; | |
// Realiza o upload de um determinado arquivo | |
$scope.upload = function (file) { | |
// Faz um get na nossa API, para obter a URL assinada | |
$http.get('/sign_s3?file_name='+file.name+'&file_type='+file.type).then(function (resp) { | |
// Obtem a URL a ser utilizada | |
var url = resp.data.signed_request_url; | |
$scope.s3Url = resp.data.result_url; | |
// Utiliza o serviço do ngFileUpload para realizar o upload para o S3 | |
// ATENÇÃO: Utilizando o método .http() e não .upload() | |
Upload.http({ | |
url: url, | |
data: file, | |
headers: { | |
'Content-Type' : file.type, | |
'x-amz-acl': 'public-read' | |
}, | |
method: 'PUT' | |
}).then(function (resp) { | |
console.log('Success ' + resp.config.data.name + 'uploaded. Response: ' + resp.data); | |
}, function (resp) { | |
console.log('Error status: ' + resp.status); | |
}, function (evt) { | |
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total); | |
$scope.progress = progressPercentage; | |
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.name); | |
}); | |
}); | |
}; | |
}]); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment