[英]How to pass base64 encoded image to php?
我想知道如何获取PHP脚本以检索我的base64编码图像,然后写入服务器? 我尝试从我的php脚本中进行发布转储,但不断收到响应,提示它为空。 我试过遵循其他一些stackoverflow指南,但是没有一个使用工厂afaik。
JS
var app = angular.module("app", ["ui.bootstrap"]);
//http://stackoverflow.com/questions/18571001/file-upload-using-angularjs
app.factory('API', function ($http) {
return {
uploadImage: function (image) {
return $http.post('/js/upload.php', image);
}
}
});
app.controller('MainController',['$scope', '$http', 'API', function($scope, $http, API) {
$scope.imageUrl = "";
$scope.template = "";
$scope.templates = [
'select an option...',
'MakeGray',
'Canny'
];
$scope.template = $scope.templates[0];
$scope.add = function() {
var f = document.getElementById('fileToUpload').files[0]; // name of image
var files = document.getElementById('fileToUpload').files;
var r = new FileReader();
r.onload = function(event){
console.log(event.target.result);
}
r.onloadend = function(e) {
var data = e.target.result;
var formData = new FormData();
$("#img1").prop("src", data);
$("#img2").prop("src", data);
formData.append("fileToUpload", f,f.name);
API.uploadImage(formData)
.success(function (imgUrl) {
$scope.imageUrl = imgUrl;
})
.error (function (error) {
});
}
r.readAsDataURL(f);
}
}]);
PHP
<?php
if(isset($_FILES['fileToUpload'])){
$errors= array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size =$_FILES['fileToUpload']['size'];
$file_tmp =$_FILES['fileToUpload']['tmp_name'];
$file_type=$_FILES['fileToUpload']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"../uploads/".$file_name);
echo " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
else{
$errors= array();
$errors[]="No image found";
print_r($errors);
}
?>
Angular在上传方面具有特殊性。
首先,您必须知道,angular的默认transformRequest函数将尝试序列化我们的FormData对象 ,因此我们用identity函数覆盖它以使数据保持完整。
接下来,用于POST请求的默认内容类型标头是“ application / json”,因此必须更改此标头,因为要上载文件。 通过设置“ Content-Type”:undefined ,浏览器自己将Content-Type设置为multipart / form-data并填写正确的边界。 手动设置“内容类型”:multipart / form-data将无法填写请求的边界参数。
查看其他可能的问题: https : //docs.angularjs.org/api/ng/service/$http
现在,您可以从$ _POST PHP全局数组中获取映像。
固定码
uploadImage: function (formData)
{
return $http.post('js/upload.php', formData,
{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
}
注意:
以下服务使用了IE9和更早版本不支持的FormData对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.