[英]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.