angularjs 實現圖片上傳實時預覽
第一部分: html部分
angularjs 主要定義了 upload-img 指令,然後還有用到ng-src, 以及angularjs必須的檔案
完整版下載網址:http://download.csdn.net/detail/u012767607/9817358
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="app"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="css/special.css" rel="stylesheet" />
<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/special.js"></script>
<script src="js/angular-1.3.0.js"></script>
<script src="js/app.js"></script>
<script src="js/app/uploadPhoto.js"></script>
</head>
<body>
<div class="sp-page-content" ng-controller="addPhotoCtrl as ctl">
<div class="sp-page-box">
<div class="sp-page-boxcolumn span1">
照片:
</div>
<div class="sp-page-boxcolumn span2">
<span class="sp-upload">
<img class="sp-upload-photo" alt="" ng-src="{{ctl.info.photo1}}" />
<input type="file" upload-img class="sp-upload-img" />
</span>
</div>
</div>
<br />
<input type="button" value="打 印" ng-click="ctl.print()" class="sp-btn-blue" />
</div>
</body>
</html>
效果圖:
第二部分:js部分
2.1. app.js部分
'use strict';
var app = angular.module('app', [
]);
2.2. /uploadPhoto.js 部分
app.controller("addPhotoCtrl", ["$http", function ($http) {
var self = this;
self.info = {
photo1: "",
photo2: ""
};
self.print = function () {
console.log(self.info);
};
}]);
app.directive("uploadImg", function () {
return {
restrict: 'AE',
scope: false,
link: function (scope, elem, attrs) {
elem.bind('click', function () {
$(this).val('');
});
elem.change(function () {
var file = this.files[0];
if (file.size > 52428800) {
alert("圖片大小不大於50M");
file = null;
return false;
}
var fileName = file.name;
var postfix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (postfix != "jpg" && postfix != "png") {
alert("圖片僅支援png、jpg型別的檔案");
fileName = "";
file = null;
return false;
}
var fileUrl = $(this).val();
$(this).parent().children(".sp-upload-photo").attr("data-url", fileUrl);
var getimg = $(this).parent().children(".sp-upload-photo");
var filereader = new FileReader();
filereader.readAsDataURL(file);
$(filereader).load(function () {
getimg.attr("src", this.result);
console.log(this.result);
});
});
}
}
});