tp5+ajax+H5 实现的文件上传

  

          
 //上传文件
$('#doc-form-file').on('change', function(){
  var formData = new FormData();
  formData.append("pic", $(this).get(0).files[0]);
  if(formData){
   	 $.ajax({
	 type: "POST",
     url:'/Api/uploadimg',
     data:formData,
	  dataType: "json",
	  cache: false,//上传文件无需缓存
      processData: false,//用于对data参数进行序列化处理 这里必须false
      contentType: false, //必须
      success: function (data){
		 console.log(data);
			
		  }
		})
   }
  
 
 
});
    public function uploadimg() {
        $file = request()->file('pic');
        //容许上传的文件类型
        $upload_image_ext = config('upload_image_ext');
        //限制的文件大小
        $upload_image_size = config('upload_image_size');
        $info = $file->validate(['size' =>intval($upload_image_size), 'ext' => $upload_image_ext])->move(ROOT_PATH . 'public' . DS . 'uploads/images/');
        if ($info) {
            $file_data = $info->getInfo();
            $data['uid']=0;
            $data['name'] = $file_data['name'];
            $data['module'] = "index";
            $path = "uploads/images/" . $info->getSaveName();
            $image = \think\Image::open($path);
// 返回图片的宽度
            $width = $image->width();
// 返回图片的高度
            $height = $image->height();
            $data['path'] = $path;
            $data['thumb'] = $path;
            $data['url'] = "";
            $data['mime'] = $file_data['type'];
            $data['ext'] = $info->getExtension();
            $data['size'] = $file_data['size'];
            $data['md5'] = $info->hash('md5');
            $data['sha1'] = $info->hash('sha1');
            $data['driver'] = "local";
            $data['download'] = "";
            $data['create_time'] = time();
            $data['update_time'] = time();
            $data['status'] = 1;
            $data['width'] = $width;
            $data['height'] = $height;
            $attachment = AttachmentModel::create($data);
            $id = $attachment['id'];
            if ($attachment['id']) {
                $return_data['path'] = $path;
                $return_data['pic'] = $id;
                $return_data2['data'] = $return_data;
                $return_data2['code'] = 200;
                echo   json_encode($return_data2);
                
            } else {
                return $this->resultArray(['code' => 201, "error" => "上传失败稍后再尝"]);
            }
        } else {
            $error = $file->getError();
            return $this->resultArray(['code' => 201, "error" => $error]);
        }
    }

 

你可能感兴趣的:(php技术,js)