Angular File Upload Demo
Single file upload and ng-model
by Felipe Alfaro
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/danialfarid-angular-file-upload/11.2.0/ng-file-upload.min.js"></script>
<div class="container" ng-app="UploadDemo" ng-controller="Main as ctrl">
<div class="col">
<h2>Single File</h2>
<label for="">model.name</label>
<input type="text" ng-model="ctrl.model.name">
<label for="">model.image</label>
<div class="upload"
ngf-drop="ctrl.upload($file)"
ngf-select="ctrl.upload($file)"
ngf-drag-over-class="'dragover'"
ngf-multiple="false"
ngf-allow-dir="false"
accept="image/*"
ngf-pattern="'image/*'"
ng-model="ctrl.model.image"
>
Click or drop image here
</div>
</div>
<div class="col">
<h2>Model</h2>
<pre class="code" ng-bind="ctrl.model | json"></pre>
</div>
</div>
CSS
body {
font-family: sans-serif;
padding: 20px;
font-size: 12px;
}
.col {
width: 50%;
float: left;
}
label {
display: block;
margin: 20px 0 4px 0;
font-family: monospace;
}
input, .upload, .code {
border: 1px solid #ddd;
border-top-color: #ccc;
padding: 6px;
border-radius: 3px;
width: 150px;
background: #fbfcfc;
}
.upload {
color: #ccc;
text-align: center;
padding: 30px 6px;
}
.dragover {
border-color: #bbb;
}
.code {
background: #e5e6e6;
color: #666;
width: auto;
}
JavaScript
(function(app){
app.controller('Main', function(Upload, $scope){
var self = this;
self.model = {
name: 'Lorem ipsum',
image: 'image.jpg'
};
self.upload = function(file){
Upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
data: {file: file}
}).then(
function suc(response){
console.log('Success %o', response);
alert(
"File uploaded! \nUploaded file: " +
response.data.result[0].name
);
//self.model.image = response.data.result[0].name;
},
function err(response){
console.log('Error: %o', response);
alert("Couldn't upload file");
},
function prg(e) {
var progressPercentage = parseInt(100.0 * e.loaded / e.total);
console.log('Progress: ' + progressPercentage + '%');
//console.log(e);
}
);
};
});
})(angular.module('UploadDemo', ['ngFileUpload']));