angularjs的文件上傳

文件上傳的基本原則

1.必須是post請求
2.將form表單的enctype屬性設置爲multipart/form-data
3.input的類型爲file

js編寫

創建uploadService.js

app.service('uploadService',function($http){

 this.upload=function(){
 	//FormData是HTML5自帶的類,理解爲表單數據
    var formData = new FormData();
    //'file'是input標籤的file類型,upload.files[0]的意思是:id爲upload,files是input標籤自帶的屬性,[0]的意思是獲取key爲0的value值,連起來是向formData中添加類型爲file,id爲upload的ipnut標籤中files屬性中key爲0的值;
    formData.append('file',upload.files[0]);
    return $http({
            url:'/upload/uploadPicture.do',
            method:'POST',
            data:formData,
            //angularjs默認的傳輸格式爲json數據,設置該Content-Type後,就相當於將form表單的enctype屬性設置爲multipart/form-data
            headers:{'Content-Type':undefined},
            //將數據以二進制的數據傳輸
            transformRequest:angular.identify        
        });
}

});

controller調用方法

app.controller('uploadController' ,function($scope,uploadService){
	$scope.img={};
	$scope.upload=function(){
   		uploadService.upload().success(function(respone){
            if(respone){
            	//respone是後臺傳過來的圖片路徑
				$scope.img.url=respone;			
            }else{
                alert('上傳失敗');
            }
        });
	}
});

頁面

<table>
	<tr>
		<td>
		<input type="file" id="file" />				                
            <button  type="button" ng-click="upload()">
				   上傳
            </button>
        </td>
		<td>
			<img  src="{{img.url}}" width="200px" height="200px">
		</td>
	</tr>						
</table>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章