js ajax上传图片到服务器
生活随笔
收集整理的這篇文章主要介紹了
js ajax上传图片到服务器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
$("#up_goods_pic").on('change',function(){var file = this.files[0];var url = webkitURL.createObjectURL(file);/* 生成圖片* ---------------------- */var $img = new Image();$img.onload = function() {//生成比例var width = $img.width,height = $img.height,scale = width / height;width = parseInt(800);height = parseInt(width / scale);//生成canvasvar canvas = document.createElement('CANVAS');var ctx = canvas.getContext('2d');canvas.height = this.height;canvas.width = this.width;ctx.drawImage($img, 0, 0, width, height);var base64 = canvas.toDataURL('image/jpeg');//發送到服務端
$.ajax({data:{data:base64},url:"/shop/upload_goods_pic",type:"POST",dataType:"json",succeed:function(data){if(data.error === 0){$("#goods_pic").append("<img src='"+data.file+"'/>");}else{alert(data.msg);}}});}$img.src = url;});
服務端
$base64_image_content = $this->input->post("data");if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){$type = $result[2];$new_file = "./".time().rand().".{$type}";if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){$this->goods_pic_model->add($new_file);die(json_encode(array("file"=>$new_file,"error"=>0)));}}die(json_encode(array("error"=>1)));?
轉載于:https://www.cnblogs.com/jh1994/p/5153656.html
總結
以上是生活随笔為你收集整理的js ajax上传图片到服务器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ArrayList迭代修改抛出Concu
- 下一篇: Jquery实现类似百度的搜索框