Simple case of PHP upload:
Html file:
Style related:
On the mobile phone, click the upload button and the camera will pop up:
<input type="file" accept="image/*;capture=camera">直接调用相机 <input type="file" accept="image/*" />调用相机 图片或者相册
PHP file:
<?php $file = $_FILES['file'];//得到传输的数据 //得到文件名称$name = $file['name'];$type = strtolower(substr($name,strrpos($name,'.')+1)); //得到文件类型,并且都转化成小写$allow_type = array('jpg','jpeg','gif','png'); //定义允许上传的类型 //判断文件类型是否被允许上传if(!in_array($type, $allow_type)){ //如果不被允许,则直接停止程序运行 return ; }//判断是否是通过HTTP POST上传的if(!is_uploaded_file($file['tmp_name'])){ //如果不是通过HTTP POST上传的 return ; }$upload_path = "./img/"; //上传文件的存放路径 //开始移动文件到相应的文件夹if(move_uploaded_file($file['tmp_name'],$upload_path.$file['name'])){ echo "Successfully!"; }else{ echo "Failed!"; }?>
A simple case of uploading using thinkphp upload class:
= 'maxSize' => 3145728, 'exts' => ('jpg', 'gif', 'png', 'jpeg'), 'rootPath' => './Public/Uploads/info/', 'savePath' => '', 'saveName' => ('uniqid',''), 'autoSub' => , 'subName' => ('date','Ymd'), upload(['result'] = 1['imgurl'] = ''['msg'] = '' = = ->upconfig['rootPath'] . ->upconfig['savePath'(!( = (, 0777, (! ['result'] = 0['msg'] = "创建保存图片的路径失败!" = \Think\Upload(->
(! ['result'] = 0['msg'] = -> = ->upconfig['rootPath'] . ['savepath'].['savename' = ('./', '/', ['result'] = 1['imgurl'] = (0 = ->upload(['attorney']);
Mobile app upload image example: API interface:
Question: When APP uploads avatars, how should php, as the API end, receive image information?
Answer 1 (see method 1): Generally, binary stream transmission is used. The client transmits binary data, the server receives it, and then file_put_contents is written to the file. That's it. The file name format and where to put the file are all defined by yourself.
Answer 2 (see method 2): The Android or IOS client simulates an HTTP Post request to the server, and the server receives the corresponding Post request (through $_FILES Obtain image resources) and return response information to the client. (This method is the same as the method of obtaining Html submission)
Method 1: Base64 encrypt the image into a string for transmission
Description: IOS or Android side: Base64 encode the image to obtain the string, and pass it to the interface
Interface side: Base64 decode the received string, and then upload it to the specified location through the file_put_contents function
/** * 图片上传 * @param $imginfo - 图片的资源,数组类型。['图片类型','图片大小','图片进行base64加密后的字符串'] * @param $companyid - 公司id * @return mixed */ public function uploadImage( $imginfo , $companyid ) { $image_type = strip_tags($imginfo[0]); //图片类型 $image_size = intval($imginfo[1]); //图片大小 $image_base64_content = strip_tags($imginfo[2]); //图片进行base64编码后的字符串 $upload = new UploaderService(); $upconfig = $upload->upconfig; if(($image_size > $upconfig['maxSize']) || ($image_size == 0)) { $array['status'] = 13; $array['comment'] = "图片大小不符合要求!"; return $array; } if(!in_array($image_type,$upconfig['exts'])) { $array['status'] = 14; $array['comment'] = "图片格式不符合要求!"; return $array; } // 设置附件上传子目录 $savePath = 'bus/group/' . $companyid . '/'; $upload->upconfig['savePath'] = $savePath; //图片保存的名称 $new_imgname = uniqid().mt_rand(100,999).'.'.$image_type; //base64解码后的图片字符串 $string_image_content = base64_decode($image_base64_content); // 保存上传的文件 $array = $upload->upload($string_image_content,$new_imgname); return $array; }
// 上传配置信息 public $upconfig = array( 'maxSize' => 3145728, //3145728B(字节) = 3M 'exts' => array('jpg', 'gif', 'png', 'jpeg'),// 'rootPath' => './Public/Uploads/info/', 'rootPath' => 'https://www.eyuebus.com/Public/Uploads/info/', ); /** * @param $string_image_content - 所要上传图片的字符串资源 * @param $new_imgname - 图片的名称,如:57c14e197e2d1744.jpg * @return mixed */ public function upload($string_image_content,$new_imgname) { $res['result'] = 1; $res['imgurl'] = ''; $res['comment'] = ''; do { $ret = true; $fullPath = $this->upconfig['rootPath'] . $this->upconfig['savePath']; if(!file_exists($fullPath)){ $ret = mkdir($fullPath, 0777, true); } if(!$ret) { // 上传错误提示错误信息 $res['result'] = 12; $res['comment'] = "创建保存图片的路径失败!"; return $res; break; } //开始上传 if (file_put_contents($fullPath.$new_imgname, $string_image_content)){ // 上传成功 获取上传文件信息 $res['result'] = 0; $res['comment'] = "上传成功!"; $res['imgname'] = $new_imgname; }else { // 上传错误提示错误信息 $res['result'] = 11; $res['comment'] = "上传失败!"; } } while(0); return $res; }
方式二:Android或者IOS客户端模拟一个HTTP的Post请求到服务器端,服务器端接收相应的Post请求后(通过$_FILES获取图片资源),返回响应信息给给客户端。(这一种方式和获取Html方式提交的方法一样)
移动端需要请求一个URL,这个URL接收POST过去的数据,比如:http://www.apixxx.net/Home/Uploader/uploadPrepare
public function uploadPrepare() { $array = array(); $post_log = print_r($_POST, true); Log::record($post_log, 'DEBUG'); $file_log = print_r($_FILES, true); Log::record($file_log, 'DEBUG'); $token = $_POST['token']; $token_str = jwt_decode($token);$user_type = $token_str['user_type']; // 设置附件上传子目录 if($user_type == 1) { $savePath = 'travel/group/' . $user_companyid . '/'; }elseif ($user_type == 2) { $savePath = 'bus/group/' . $user_companyid . '/'; }elseif ($user_type == 3) { $savePath = 'driver/group/' . $user_companyid . '/'; }else { $array['status'] = 3; $array['comment'] = '非法用户!'; return $array; } $this->upconfig['savePath'] = $savePath; // 保存上传的文件(单张) // $res = $this->upload($_FILES['file']); // 保存上传的文件(多张) 移动端的表单name=“xxx[]”,支持多张图片 $res = $this->upload(); $array['status'] = $res['status']; $array['comment'] = $res['comment']; $array['responseParameters']['img_url'] = $res['img_url']; echo json_encode($array); } protected function upload() { $res['status'] = 1; $res['imgurl'] = ''; $res['comment'] = ''; do { $ret = true; $fullPath = $this->upconfig['rootPath'] . $this->upconfig['savePath']; if(!file_exists($fullPath)){ $ret = mkdir($fullPath, 0777, true); } if(!$ret) { // 上传错误提示错误信息 $res['status'] = 1; $res['comment'] = "创建保存图片的路径失败!"; break; } // 实例化上传类 $upload = new \Think\Upload($this->upconfig);// // 上传单个文件 // $info = $upload->uploadOne($file); // 上传多个文件 $infos = $upload->upload(); // 上传的图片数量 $file_count = 0; foreach ($_FILES as $file_k => $file_v) { foreach ($file_v["size"] as $k => $v) { if($v == 0) { continue; } $file_count += 1; } } Log::record("info_log", 'DEBUG'); $info_log = print_r($infos,true); Log::record($info_log, 'DEBUG'); if(!$infos) { // 上传错误提示错误信息 $res['status'] = 2; $res['comment'] = $upload->getError(); } else { // 获取的上传成功的图片数量 $info_count = 0; // 上传成功 获取上传文件信息 foreach($infos as $k => $v) { $imgurl[$v['key']][] = str_replace('./', '/', $this->upconfig['rootPath'] . $v['savepath'].$v['savename']); $info_count += 1; } if($file_count != $info_count) { $res['status'] = 1; $res['comment'] = "上传失败!上传的多张图片,没有全部上传成功"; }else { $res['status'] = 0; $res['comment'] = "上传成功!"; $res['img_url'] = $imgurl; } } } while(0); return $res; }
相关推荐:
相关推荐:
The above is the detailed content of PHP about AIP image upload interface. For more information, please follow other related articles on the PHP Chinese website!

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software