我正在尝试使用一些其他数据将图像发送到服务器。我的问题是图像没有保存在其他记录所在的服务器上。
下面是我的 .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>
我尝试使用print_r($ _ REQUEST);
在PHP中打印值image的值为null。
如何将图像发送到服务器?
答案 0 :(得分: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!