2.html端: index.html
name:
gender:male female
photo:
$("[link=sub]").click(function (){
var data = new FormData($('#uploadForm')[0]);
$.ajax({
url: 'a.php',
type: 'POST',
data: data,
dataType: 'json',
cache: false,
processData: false,
contentType: false
}).done(function(ret){
if(ret['isSuccess']){
var result = '';
result += 'name=' + ret['name'] + '
';
result += 'gender=' + ret['gender'] + '
';
result += '';
$('#result').html(result);
}else{
alert('提交失敗');
}
});
return false;
});
//type=file 一旦change就上传图片
$("[name=photo]").change(function (){
var data = new FormData($('#uploadForm')[0]);
$.ajax({
url: 'a.php',
type: 'POST',
data: data,
dataType: 'json',
cache: false,
processData: false,
contentType: false
}).done(function(ret){
if(ret['isSuccess']){
var result = '';
result += 'name=' + ret['name'] + '
';
result += 'gender=' + ret['gender'] + '
';
result += '';
$('#result').html(result);
}else{
alert('提交失敗');
}
});
return false;
});
3.html提交给自己的程序a.php (如果用js提给接口会存在跨域问题)
//文件路径
$file="@".$_FILES['photo']['tmp_name'];
//获取文件扩展名
$file_name_arr=pathinfo($_FILES['photo']['name']);
$file_extension=$file_name_arr['extension'];
$name=$_POST['name'];
$gender=$_POST['gender'];
$ch = curl_init();
$post_data = array(
'name' => $name,
'gender' => $gender,
'file' => $file,
'file_extension'=>$file_extension,
);
curl_setopt($ch, CURLOPT_HEADER, false);
//启用时会发送一个常规的POST请求,类型为:application/x-www-form-urlencoded,就像表单提交的一样。
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //得到返回值且不显示在页面上
curl_setopt($ch, CURLOPT_URL, 'https://www.wlphp.com/myblog_demo/api/uploadfile/index.php'); //可以理解为接口地址
$info= curl_exec($ch); //可以理解为接口返回值
curl_close($ch);
//完全输出接口返回值
echo $info;
4.php接口:
error_reporting(0);
$file_extension=$_POST['file_extension'];
$filename = "./upload/".time().time().".".$file_extension;
if(move_uploaded_file($_FILES['file']['tmp_name'], $filename)){
$response['isSuccess'] = true;
$response['name'] = $_POST['name'];
$response['gender'] = $_POST['gender'];
$response['photo'] = dirname('http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]).$filename;
}else{
$response['isSuccess'] = false;
}
echo json_encode($response);
版权声明:若无特殊注明,本文皆为《菜鸟站长》原创,转载请保留文章出处。
本文链接:如何把文件提交给接口上传到服务器(php版) - http://wlphp.com/?post=62