web前端開發(fā)upload上傳頭像js示例代碼
這次分享一個簡易的上傳頭像示例,其大致流程為:
一、將選擇的圖片轉為base64字符串
function preview(file) {//預覽圖片得到圖片base64 var prevDiv = document.getElementById('preview'); if (file.files && file.files[0]) { var reader = new FileReader(); reader.onload = function(evt){ prevDiv.innerHTML = '<img src="' + evt.target.result + '" />'; } reader.readAsDataURL(file.files[0]); } else { prevDiv.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>'; } }
上面的方法可將選擇的圖片轉為base64預覽,此時可以打樁看看base64到底是什么東東。
二、根據(jù)(阿里云)上傳要求,對該圖像base64去頭等處理
var binaryblob = function (s, type) {//blob對象 var byteString = atob(s); var array = []; for (var i = 0; i < byteString.length; i++) { array.push(byteString.charCodeAt(i)); } return new Blob([new Int8Array(array)], {type: type}); }; var binaryPictureBlob = function (dataUrl, filterHead) {//上傳base64去頭 var s = filterHead ? dataUrl.replace(/^data:image\/(png|jpeg|pjpeg|bmp|gif|x-png);base64,/, "") : dataUrl; return binaryblob(s, "image/jpeg"); };
此時將base64去頭等處理后返回一個blob對象用于上傳阿里云。以上方法最好寫在service、factory里,以后有圖像上傳需求時方便直接調(diào)用,盡量不要寫在controller內(nèi)。
三、第一次請求
$scope.save=function(){//保存 var pic=binaryPictureBlob($('#preview img').attr('src'),true);//調(diào)用該方法得到上傳數(shù)據(jù) console.log(pic); $http({//接口參數(shù) url:'', method:'', headers:{}, data:{} }).success(function(data){ console.log(data); //這里講進行第二次請求 }).error(function(err1,header1,config1,status1){//處理響應失敗 console.log(err1,header1,config1,status1); }) }
點擊保存按鈕后第一次請求是上傳到本地服務器,實際是上傳一些該圖像的標記等信息。上傳成功后會返回一個該圖像對應的阿里云地址和一個阿里云上傳圖像的地址,此時該圖像地址暫不可用。
四、第二次請求
$http({ method:'PUT', url:data.UrlForPut, headers: { 'Content-Type':' ', }, data:pic//圖像base64字符串去頭等處理后的圖片信息blob }).success(function(data2){ $scope.imgSrc=data.Url;//將服務器的數(shù)據(jù)的url賦值圖片鏈接 }).error(function(err2,header2,config2,status2){//處理響應失敗 console.log(err2,header2,config2,status2); });
注意:
此時請求的url是第一次請求返回的一個固定地址(我這里是--data.UrlForPut)。
頭部信息處避免阿里云上傳時報錯寫成'Content-Type':' '或者根據(jù)阿里云要求上傳header。
第二次請求成功后圖片的地址是第一次返回的該圖像的地址(此處是個大坑,data.Url不要寫成data2.Url了)。
五、此時應該都ok了,好好欣賞靚照吧!
最后附上完整代碼,望指教!
友情提示:在復制代碼測試時請求參數(shù)自己加上哦!
<!DOCTYPE html> <html ng-app="webPhotos"> <head lang="zh-CN"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title>photos</title> <style> div{text-align:center;border:1px solid #ddd;} button,div{margin:10px auto} button{border:0;width:200px;height:30px;line-height:30px;font-size:1pc;color:#333;background-color:#0ff;cursor:pointer;border-radius:5px} button:hover{background-color:#db7093} #preview,.show-img{width:200px;height:200px;} #preview img,.show-img img{width:100%;height:100%;} .file{position:relative;display:block;width:200px;height:30px;line-height:30px;background:#9acd32;border-radius:5px;margin:10px auto;overflow:hidden;color:#1e88c7;text-decoration:none;text-indent:0} .file input{position:absolute;font-size:75pt;right:0;top:0;opacity:0} .file:hover{background:#aadffd;border-color:#78c3f3;color:#004974;text-decoration:none} </style> </head> <body> <div ng-controller="photos"> <a href="javascript:;" class="file"> <span>選擇文件</span> <input type="file" onchange="preview(this)" /> </a> <button class="save" ng-click="save()">保存</button> <h2>頭像預覽</h2> <div id="preview"></div> <h2>上傳成功后展示頭像</h2> <div class="show-img"> <img ng-src={{imgSrc}} alt=""/> </div> </div> <script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script> <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> <script> function preview(file) {//預覽圖片得到圖片base64 var prevDiv = document.getElementById('preview'); if (file.files && file.files[0]) { var reader = new FileReader(); reader.onload = function(evt){ prevDiv.innerHTML = '<img src="' + evt.target.result + '" />'; } reader.readAsDataURL(file.files[0]); } else { prevDiv.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>'; } } //以上代碼最好寫在service或factory里 angular.module('webPhotos',['ng']) .controller('photos',function($scope,$http){ var binaryblob = function (s, type) {//blob對象 var byteString = atob(s); var array = []; for (var i = 0; i < byteString.length; i++) { array.push(byteString.charCodeAt(i)); } return new Blob([new Int8Array(array)], {type: type}); }; var binaryPictureBlob = function (dataUrl, filterHead) {//上傳base64去頭 var s = filterHead ? dataUrl.replace(/^data:image\/(png|jpeg|pjpeg|bmp|gif|x-png);base64,/, "") : dataUrl; return binaryblob(s, "image/jpeg"); }; $scope.save=function(){//保存 var pic=binaryPictureBlob($('#preview img').attr('src'),true);//調(diào)用該方法得到上傳數(shù)據(jù) $http({//接口參數(shù) url:'', method:'', headers:{}, data:{} }).success(function(data){//此時上傳到本地服務器成功,實際上只是上傳了與此圖片有關的標記,圖片信息還未上傳 $http({ method:'PUT', url:data.UrlForPut,//上傳到本地服務器已經(jīng)生成地址,但要上傳到阿里云后地址才生效有上傳的圖像顯示 headers: { 'Content-Type':' ',//避免阿里云上傳時報錯或者根據(jù)阿里云要求上傳header }, data:pic//圖像base64字符串去頭等處理后的圖片信息 }).success(function(data2){//將圖像信息從服務器上傳到阿里云 $scope.imgSrc=data.Url;//將服務器的數(shù)據(jù)的url賦值圖片鏈接 }).error(function(err2,header2,config2,status2){//處理響應失敗 console.log(err2,header2,config2,status2); }); }).error(function(err1,header1,config1,status1){//處理響應失敗 console.log(err1,header1,config1,status1); }) } }) </script> </body> </html>
更多精彩內(nèi)容請參考專題《ajax上傳技術匯總》,《javascript文件上傳操作匯總》和《jQuery上傳操作匯總》進行學習。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
php is_numberic函數(shù)造成的SQL注入漏洞
這篇文章主要介紹了php is_numberic函數(shù)造成的SQL注入漏洞和解決辦法,需要的朋友可以參考下2014-03-03