2015-11-08 122 views
0

我想用一些額外的數據發送圖像到服務器。我的問題是,圖像沒有得到保存在其他錄音的​​服務器上。如何在AngularJS上將圖像發送到服務器?

下面

是我的.html代碼:

<div class="widget uib_w_4 d-margins" data-uib="media/file_input" data-ver="0"> 
    <input type="file" name="image" id="image" 
     accept="image/jpeg, image/png, image/gif" 
     ng-model="image" class="ng-pristine ng-untouched ng-valid"> 
</div> 
<div class="widget uib_w_5 d-margins" data-uib="media/text" data-ver="0"> 
    <div class="widget-container left-receptacle"></div> 
    <div class="widget-container right-receptacle"></div> 
    <div> 
     <p>Username:</p> 
    </div> 
</div> 

JS代碼

<script> 
var app = angular.module('myApp', []); 
app.controller('customersCtrl', function($scope, $http) { 
    $scope.SendData = function() 
    var data = $.param({ 
     image: $scope.image, 
     username: $scope.username, 
    }); 

    var config = { 
     headers: { 
      'Content-Type': 'application/x-www-form-urlencoded; 
       charset = utf - 8; 
       ' 
     } 
    } 
    var param = getParameterByName('id'); 
    $http.post('myrurl.php', data, config) 
     .success(function(data, status, headers, config) { 
     window.location.href = 'view.html'; 
    }) 
     .error(function(data, status, header, config) { 
     alert('Please retry'); 
    }); 
}; 
}); 
< /script> 

我試圖在PHP中使用的print_r($ _ REQUEST)打印的價值;

圖像的值爲空。

如何將圖像發送到服務器?

+1

你如何處理事情在服務器端? – MayK

+0

服務器代碼是好的我試圖通過圖像值打印請求檢查是空的 – mdeveloper

+0

我在服務器上使用一個單獨的設置點,僅用於圖像上傳。用戶必須首先上傳圖像,然後發送表單數據..但無論如何,我將圖像作爲formData準備好,然後將其發送到服務器 – MayK

回答

0

很容易。一個好的方法可以是Base64對圖像進行編碼,然後將該Base64發送到服務器;最好的部分是PHP本身支持解碼Base64。

你可以這樣做:

<!-- In your HTML file --> 
<input type="file" id="file" /> 
<input type="submit" ng-click"uploadFile" value="Upload File"/> 

然後,在你的JavaScript:

$("#file").on('change', function(event) { 

    var reader = new FileReader(); 
    reader.onload = function(loadEvent) { 

     $scope.fileData = loadEvent.target.result; 
     $scope.$apply(); 

    }; 

    reader.readAsDataURL(event.target.files[0]); 

}); 

$scope.uploadFile = function() { 

    if ($scope.fileData === null || $scope.fileData === "" || !($scope.fileData)) { 
     alert("No file has been uploaded"); 
     return; 
    } 


    var dtx = eval("(" + atob($scope.fileData.substring("data:application/json;base64,".length)) + ")"); 

    $http.get('yourScript.php?data=' + encodeURIComponent(JSON.stringify(dtx))).then(function(response) { 

     if(response.data.status_code == 200) { 

      // Done! 

     } else { ERROR } 

    }); 

}; 

最後,在你的PHP文件就可以了:

$imageData = base64_decode($_GET[ 'data' ]); // Now you have a binary image file. Do whatever you want! 
+0

對不起,它不起作用 – mdeveloper

+1

你能告訴我更多關於錯誤?另外,請記住,這段代碼只是一個例子。您必須根據自己的需要進行編輯。 – weirdpanda

+0

我一直給出錯誤「No file has been uploaded」 – mdeveloper