如何使用FormData API发出POST请求 [英] How to make POST requests with the FormData API
本文介绍了如何使用FormData API发出POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用http.post
将用户名和form_data对象传递给php文件,当我只传递form_data时,它可以上传我的图片。但我想传递一些其他信息,如用户名。请帮我如何传递http.post
中的其他数据这里是我的php文件。
I want to pass the username and form_data object to the php file using http.post when i pass only form_data it works my picture upload. but i want to pass some other information like username as well. please help me how to pass other data in http.post And here is my php file.
<?php include "connectdb.php";
$data=json_decode(file_get_contents("php://input"));
$name=$dbhandle->real_escape_string($data->susername);
if (!empty($_FILES)) {
$date=2;
$path = 'fooditem/'. $_FILES['file']['name'];
if (move_uploaded_file($_FILES['file']['tmp_name'],$path)) {
$query="INSERT INTO `login`(`id`,`type`,`img`) VALUES('".$name."','".$date."','".$_FILES['file']['name']."')";
if($dbhandle->query($query)){
echo 'File Uploaded';
}
else
echo 'File Uploaded But Not Saved';
}
}else{
echo 'Some Error';
}
myapp.directive("fileInput",function($parse){
return{
link: function($scope,element,attrs){
element.on("change",function(event){
var files = event.target.files;
$parse(attrs.fileInput).assign($scope, element[0].files);
$scope.$apply();
// console.log(files[0].name);
});
}
}
});
myapp.controller("myController",function($scope,$http){
$scope.signup = function(){
var form_data = new FormData();
angular.forEach($scope.files,function(file){
form_data.append('file',file);
});
$http.post("picupload.php",{'susername':$scope.susername,form_data})
.then(function(response){
console.log(response);
})
});
<input type="text" ng-model="username" name="username">
<input type="file" file-input="files" accept="image/*" />
<input type="submit" value="SIGN UP" ng-click="signup()"
name="signup_btn" class="btn btn-primary">
推荐答案
你可以添加类似这样的事情:
You can add something like this:
myapp.controller("myController",function($scope,$http){
$scope.signup = function(){
var form_data = new FormData();
angular.forEach($scope.files,function(file){
form_data.append('file',file);
});
form_data.append('susername',$scope.susername); // new line
var config = {headers: { 'Content-type': undefined } };
$http.post("picupload.php",form_data, config)
.success(function(response){
alert(response);
});
}
我不确定PHP,但谷歌搜索后我发现在php' susername'可以检索如下:
I'm not sure about PHP but after googling I found that in php 'susername' can retrieved as below:
$_POST['susername'];
这篇关于如何使用FormData API发出POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文