[英]Upload a file with AngularJS and PHP
我想在使用AngularJS前端和PHP后端时上传文件。 当我将Angular放在一边时,我的HTML表单将如下所示:
<form enctype="multipart/form-data" action="process.php" method="POST" >
File: <input name="userfile" type="file"/>
<input type="submit" value="Send File" />
</form>
我在process.php中的 PHP是这样的:
$tmpFilePath = $_FILES['userfile']['tmp_name'];
if ($tmpFilePath != ""){
$newFilePath = "my-uploads/" . $_FILES['userfile']['name'];
move_uploaded_file($tmpFilePath, $newFilePath);
}
到目前为止,一切正常,单击提交即可上传文件。 但是我需要用Angular来完成整个事情。 因此,我将HTML更改为:
<form ng-submit="processForm()" >
File: <input name="userfile" type="file" ng-model="formData.file"/>
<input type="submit" value="Send File" />
</form>
我的Angular控制器中的代码如下所示:
$scope.formData = '';
$scope.processForm = function() {
$http({
method : 'POST',
url : 'process.php',
data : $.param($scope.formData),
headers : { 'Content-Type': undefined }
})
.success(function(data) {
console.log(data);
console.log('success!');
})
.error(function(data) {
console.log(data)
});
};
当我单击“提交”时,控制台会告诉我“成功!”,但是没有文件上传。 我认为问题是$ http-request中的“数据”和“标题”? 但是我对此不确定,因此到目前为止在网上都找不到解决方案。 有谁知道我在使用angulars $ http-functionity时必须上传文件吗?
如果不使用HTML5文件API,Angular无法使用AJAX上传文件。
更改代码以使用文件API并提交二进制内容,或使用外部库(例如angular-file-upload) 。
<input type='file' name="Filename" data-ng-file-select onchange="scope.setFile(this)" id="imgInp"> (html)
window.scope = $scope;
$scope.setFile = function (ele) {
var photofile = ele.files[0];
var reader = new FileReader();
console.log(photofile);
reader.onload = function (e) {
$scope.$apply(function () {
console.log(e);
$scope.prev_img = e.target.result;
$scope.prev_img = angular.copy($scope.prev_img);
$http({
method: 'POST',
url: 'api/1.php',
data: { 'imagepath': $scope.prev_img },
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
})
.success(function (data) {
console.log(data);
})
.error(function (error) {
$scope.data.error = error;
});
});
}; (angurlarjs)
<?php
include 'db_connect.php';
include 'functions.php';
//$levels = array();
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$idUser = $request->imagepath;
echo $idUser;
// CLOSE CONNECTION
mysqli_close($mysqli);
echo json_encode($json);
?>(php)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.