Last active
July 21, 2016 02:35
-
-
Save alanwei43/331e24a2be5c34611f2c0427f1d74c62 to your computer and use it in GitHub Desktop.
Angular Files Upload
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> | |
<head> | |
<title>Angular Files Upload</title> | |
<meta charset="utf-8" /> | |
<script src="http://cdn.bootcss.com/angular.js/1.3.18/angular.js"></script> | |
</head> | |
<body> | |
<div ng-app="FUApp"> | |
<div ng-controller="BodyCtrl as main"> | |
<label> | |
<span>Ajax URL: </span> | |
<input ng-model="main.params.uploadUrl" /> | |
</label> | |
<hr /> | |
<div file-upload upload-url="main.params.uploadUrl"> </div> | |
</div> | |
</div> | |
<script> | |
angular.module("FUApp", []) | |
.directive("fileUpload", function ($timeout, $http) { | |
return { | |
templateUrl: "directive-file-upload.html", | |
scope: { | |
paramUploadUrl: "=uploadUrl" | |
}, | |
transclude: true, | |
link: function (scope, tEle, tAttrs) { | |
scope.data = { | |
files: [] | |
}; | |
tEle.find("input").on("change", function () { | |
scope.data.files.splice(0); | |
angular.forEach(this.files, function (file) { | |
var reader = new FileReader(); | |
reader.readAsDataURL(file); | |
var result = { | |
original: file, | |
base64: undefined | |
}; | |
reader.onloadend = function () { | |
scope.$apply(function () { | |
result.base64 = reader.result; | |
}); | |
} | |
scope.$apply(function () { | |
scope.data.files.push(result); | |
}); | |
}); | |
}); | |
}, | |
controller: function ($scope) { | |
var main = $scope; | |
main.upload = function () { | |
var form = new FormData(); | |
angular.forEach($scope.data.files, function (f) { | |
form.append(f.original.name, f.original); | |
}); | |
$http({ | |
url: $scope.paramUploadUrl, | |
method: "POST", | |
data: form, | |
transformRequest: angular.identity, | |
headers: { "Content-Type": undefined } | |
}).then(function (ngResponse) { | |
console.log(ngResponse.data); | |
}); | |
}; | |
} | |
}; | |
}) | |
.controller("BodyCtrl", function () { | |
this.params = { | |
uploadUrl: "/MockApi/FileUpload" | |
}; | |
}); | |
</script> | |
</body> | |
</html> |
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
<div> | |
<label> | |
<span>请选择文件</span> | |
<input type="file" value="" multiple /> | |
</label> | |
</div> | |
<ol> | |
<li ng-repeat="img in data.files"> | |
<img ng-src="{{img.base64}}" style="width: 200px" /> | |
</li> | |
</ol> | |
<button ng-click="upload()">upload</button> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment