js代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>aaaa</title>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<input type="file" id="file_upload"/>
<input type="button" value="上传图片" id="upload"/>
</body>
<script type="text/javascript">
$(function() {
function ajaxFileUpload(){
var formData = new FormData();
formData.append('file',$("#file_upload")[0].files[0]); //将文件转成二进制形式
$.ajax({
type:"post",
url:"http://127.0.0.1/demo.php",
async:false,
contentType: false, //这个一定要写
processData: false, //这个也一定要写,不然会报错
data:formData,
dataType:'text', //返回类型,有json,text,HTML。这里并没有jsonp格式
success:function(data){
console.log(data);
},
error:function(XMLHttpRequest, textStatus, errorThrown, data){
console.log(errorThrown);
}
});
}
$("#upload").click(function(){
ajaxFileUpload();
});
});
</script>
</html>
后端php代码
<?php
header("Access-Control-Allow-Origin: *");
echo json_encode(array('code'=>200,'msg'=>''));
网友评论