ajax跨域上传图片
-
前台页面
var data = new FormData(); data.append('file', file); data.append('app', 'goods'); $.ajax({ url:"http://www.wangh.com/index.php", dataType:"json", type:'post', data:data, cache: false, contentType: false, processData: false, success:function(res){ console.log('图片上传成功'); console.log('res:'+res); if(res.code == 0){ console.log('上传_ok!'); } else{ console.log('上传_err!'); alert(res.msg); return false; } },error: function () { console.log('图片上传失败'); alert('图片上传失败'); return false; } });
-
PHP
//如果需要设置允许所有域名发起的跨域请求,可以使用通配符 * header("Access-Control-Allow-Origin: *");
$log = $_FILES; file_put_contents('log.txt',json_encode($log),FILE_APPEND); $imgname = $_FILES['file']['name']; $tmp = $_FILES['file']['tmp_name']; $filepath = './uimg/'.rand(999,100000000000); file_put_contents('log.txt','img_name:',$filepath.$imgname); if(move_uploaded_file($tmp,$filepath.$imgname)){ file_put_contents('log.txt','上传成功',FILE_APPEND); $data_result = array( 'code' => 0 , 'message' => 'this is ok' ); }else{ file_put_contents('log.txt','上传失败',FILE_APPEND); $data_result = array( 'code' => 0 , 'message' => 'this is err' ); }
echo json_encode($data_result);