thinkphp5实现ajax图片上传,压缩保存到服务器

javascript 复制代码
<div class="warp">
      <input type="file" id="file"  accept="image/*" onchange="upimg(this)" />
 </div>
<img src="" />
<script>
    //上传图片方法
     function upimg(obj){
         var fileData = obj.files[0];//这是我们上传的文件
         console.log(fileData)
         var formData = new FormData();
         // 服务端要求参数是 pic1
         formData.append('image',fileData);
         $.ajax({
             url:"{:url('user/upmemberphoto')}",
             type:'post',
             data:formData,
             cache: false, //上传文件不需要缓存
             processData: false, // 告诉jQuery不要去处理发送的数据
             contentType: false, // 告诉jQuery不要去设置Content-Type请求头
             success:function(data){
                 console.log(data);
                 // 设置图片预览功能
                 $('.head-img').attr('src',data.picAddr);
             }
         })
     }
</script>

thinkphp压缩图片插件官方地址

使用Composer安装ThinkPHP5的图像处理类库:

composer require topthink/think-image

php 复制代码
    //上传会员照片接口
    public function upmemberphoto(){
        // 获取上传文件
        $file =  request()->file('image');


        $url=ROOT_PATH.'/public/uploads/member';

        // 移动到本地服务器==这个是保存原图
        $info = $file->move($url);

        if ($info) {
            $tempstr=$info->getSaveName();
            $tempstr=str_replace("\\","/",$tempstr);

            $imgurl=$url.'/'.$tempstr;

            // 按照原图的比例生成一个最大为320*320的缩略图并保存为thumb.png==这个是压缩后保存
            $image = \think\Image::open($imgurl);
            $image->thumb(320,320)->save($imgurl);

            return ['code' => 200, 'message' =>'上传成功','data'=>'/uploads/member/'.$tempstr];
        } else {
            // 文件上传失败
            return ['code' => 400, 'message' => '上传失败'];
        }
    }
相关推荐
niucloud-admin7 小时前
web 端前端
前端
张太行_8 小时前
Linux静态库:多模块高效管理
linux·运维·服务器
ID_180079054738 小时前
YouTube item_get_video接口认证方式:API密钥与OAuth2.0的选择与应用
服务器·windows·microsoft
wgl6665208 小时前
Linux---基础IO!
linux·运维·服务器
科技块儿9 小时前
使用强大的离线IP地址定位库IP数据云获取数据信息
网络·tcp/ip·php
Ancelin安心9 小时前
kali-dirsearch的使用
linux·运维·服务器·python·计算机网络·web安全·网络安全
jun_bai9 小时前
python+Java的网盘程序升级版。无感知备份文档,保护数据资产利器。
运维·服务器
上海云盾-高防顾问9 小时前
筑牢网络防线:境外恶意网址与IP防范指南
服务器·网络·安全
胖者是谁10 小时前
EasyPlayerPro的使用方法
前端·javascript·css
EndingCoder10 小时前
索引类型和 keyof 操作符
linux·运维·前端·javascript·ubuntu·typescript