图片上传
<input id="file-input" type="file" class="file" accept="image/jpeg,image/gif"> <img id="img" class="file-preview-image" src="">
<script> $(function(){ $("#file-input").change(function () { var url="http://127.0.0.6/index.php/service/image/?action=upload"; uploadImg(url,this); }); }); function readURL(input, tmpimg) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { if (!/image/.test(e.target.result)) { alert('请上传图片格式...'); return false; } tmpimg.attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } function uploadImg(url,e){ var file = e.files[0]; $("#img-div").before(str); var $img = $("#img"); readURL(e, $img); var formData = new FormData(); formData.append('picture', file); $.ajax({ type: "POST", //必须用post url: url , crossDomain: true, jsonp: "jsoncallback", data: formData, contentType: false, //必须 processData: false, success: function (data) { …… }, error:function(){ …… } }); } </script>
如果要上传的url是跨域的,请在服务端加上
header("Access-Control-Allow-Origin:*"); header('Access-Control-Allow-Credentials:true');