Skip to content

Instantly share code, notes, and snippets.

@iffy
Created February 25, 2016 15:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save iffy/ea5e7278ab0b4e6ebf54 to your computer and use it in GitHub Desktop.
Save iffy/ea5e7278ab0b4e6ebf54 to your computer and use it in GitHub Desktop.
Angular 1 File Upload example
<!DOCTYPE html>
<html lang="en">
<body ng-app="myapp" ng-controller="UploadCtrl">
<input type="file" file-change="upload">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
// the javascript
var app = angular.module('myapp', []);
//
// Reusable Uploader service.
//
app.factory('Uploader', function($q, $rootScope) {
this.upload = function(url, file) {
var deferred = $q.defer(),
formdata = new FormData(),
xhr = new XMLHttpRequest();
formdata.append('file', file);
xhr.onreadystatechange = function(r) {
if (4 === this.readyState) {
if (xhr.status == 200) {
$rootScope.$apply(function() {
deferred.resolve(xhr);
});
} else {
$rootScope.$apply(function() {
deferred.reject(xhr);
});
}
}
}
xhr.open("POST", url, true);
xhr.send(formdata);
return deferred.promise;
};
return this;
})
//
// fileChange directive because ng-change doesn't work for file inputs.
//
app.directive('fileChange', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('change', function() {
scope.$apply(function() {
scope[attrs['fileChange']](element[0].files);
})
})
},
}
})
//
// Example controller
//
app.controller('UploadCtrl', function($scope, $http, Uploader) {
$scope.upload = function(files) {
var r = Uploader.upload('/uploads', files[0]);
r.then(
function(r) {
// success
},
function(r) {
// failure
});
}
});
</script>
</body>
</html>
from flask import Flask, request, send_file
app = Flask(__name__)
@app.route("/", methods=['GET'])
def index():
return send_file('index.html')
@app.route("/uploads", methods=['POST'])
def uploads():
# See more http://flask.pocoo.org/docs/0.10/patterns/fileuploads/
upload = request.files['file']
print 'Received file', upload.filename
app.run()
$ pip install Flask
$ python server.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [25/Feb/2016 08:27:56] "GET / HTTP/1.1" 200 -
Received file something.txt
127.0.0.1 - - [25/Feb/2016 08:28:01] "POST /uploads HTTP/1.1" 500 -
@prakalpaprakash
Copy link

how can I send an image and text field to the server?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment