Home Backend Development PHP Tutorial PHP about AIP image upload interface

PHP about AIP image upload interface

Mar 10, 2018 pm 01:37 PM
php upload interface

Simple case of PHP upload:

Html file:


<html><form action="index.php" name="form" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" name="submit" value="上传" /></form></html>
Copy after login

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/*" />调用相机 图片或者相册
Copy after login

PHP file:

<?php$file = $_FILES[&#39;file&#39;];//得到传输的数据

//得到文件名称$name = $file[&#39;name&#39;];$type = strtolower(substr($name,strrpos($name,&#39;.&#39;)+1)); //得到文件类型,并且都转化成小写$allow_type = array(&#39;jpg&#39;,&#39;jpeg&#39;,&#39;gif&#39;,&#39;png&#39;); //定义允许上传的类型
//判断文件类型是否被允许上传if(!in_array($type, $allow_type)){    //如果不被允许,则直接停止程序运行
    return ;
}//判断是否是通过HTTP POST上传的if(!is_uploaded_file($file[&#39;tmp_name&#39;])){    //如果不是通过HTTP POST上传的
    return ;
}$upload_path = "./img/"; //上传文件的存放路径
//开始移动文件到相应的文件夹if(move_uploaded_file($file[&#39;tmp_name&#39;],$upload_path.$file[&#39;name&#39;])){    echo "Successfully!";
}else{    echo "Failed!";
}?>
Copy after login

A simple case of uploading using thinkphp upload class:

    
      = &#39;maxSize&#39;    =>    3145728,         
        &#39;exts&#39;       =>    (&#39;jpg&#39;, &#39;gif&#39;, &#39;png&#39;, &#39;jpeg&#39;),
        &#39;rootPath&#39;   =>    &#39;./Public/Uploads/info/&#39;,
        &#39;savePath&#39;   =>    &#39;&#39;,                          
        &#39;saveName&#39;   =>    (&#39;uniqid&#39;,&#39;&#39;),
        &#39;autoSub&#39;    =>    ,                       
        &#39;subName&#39;    =>    (&#39;date&#39;,&#39;Ymd&#39;),  upload([&#39;result&#39;] = 1[&#39;imgurl&#39;] = &#39;&#39;[&#39;msg&#39;] = &#39;&#39; =  = ->upconfig[&#39;rootPath&#39;] . ->upconfig[&#39;savePath&#39;(!( = (, 0777, (!
                [&#39;result&#39;] = 0[&#39;msg&#39;] = "创建保存图片的路径失败!"
             =  \Think\Upload(->
Copy after login
(!
                [&#39;result&#39;] = 0[&#39;msg&#39;] = ->
                 =  ->upconfig[&#39;rootPath&#39;] . [&#39;savepath&#39;].[&#39;savename&#39; = (&#39;./&#39;, &#39;/&#39;, [&#39;result&#39;] = 1[&#39;imgurl&#39;] = (0 
         = ->upload([&#39;attorney&#39;]);
Copy after login

Mobile app upload image example: API interface:

Question: When APP uploads avatars, how should php, as the API end, receive image information?

The upload part of the code is not a problem, the main problem is how the server side can receive the image information from the APP side. Under the B/S architecture, you can set enctype="multipart/form-data" directly through the form form, and the image information will be in the $_FILES array. So is this also true in C/S mode?

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 - 图片的资源,数组类型。[&#39;图片类型&#39;,&#39;图片大小&#39;,&#39;图片进行base64加密后的字符串&#39;]
     * @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[&#39;maxSize&#39;]) || ($image_size == 0)) {            $array[&#39;status&#39;] = 13;            $array[&#39;comment&#39;] = "图片大小不符合要求!";            return $array;
        }        if(!in_array($image_type,$upconfig[&#39;exts&#39;])) {            $array[&#39;status&#39;] = 14;            $array[&#39;comment&#39;] = "图片格式不符合要求!";            return $array;
        }        // 设置附件上传子目录
        $savePath = &#39;bus/group/&#39; . $companyid . &#39;/&#39;;        $upload->upconfig[&#39;savePath&#39;] = $savePath;        //图片保存的名称
        $new_imgname = uniqid().mt_rand(100,999).&#39;.&#39;.$image_type;        //base64解码后的图片字符串
        $string_image_content = base64_decode($image_base64_content);        // 保存上传的文件
        $array = $upload->upload($string_image_content,$new_imgname);        return $array;
    }
Copy after login
    // 上传配置信息
    public $upconfig = array(        &#39;maxSize&#39;    =>    3145728,         //3145728B(字节) = 3M
        &#39;exts&#39;       =>    array(&#39;jpg&#39;, &#39;gif&#39;, &#39;png&#39;, &#39;jpeg&#39;),//        &#39;rootPath&#39;   =>    &#39;./Public/Uploads/info/&#39;,
        &#39;rootPath&#39;   =>    &#39;https://www.eyuebus.com/Public/Uploads/info/&#39;,
    );    /**
     * @param $string_image_content - 所要上传图片的字符串资源
     * @param $new_imgname - 图片的名称,如:57c14e197e2d1744.jpg
     * @return mixed     */
    public function upload($string_image_content,$new_imgname) {        $res[&#39;result&#39;] = 1;        $res[&#39;imgurl&#39;] = &#39;&#39;;        $res[&#39;comment&#39;] = &#39;&#39;;        do {            $ret = true;            $fullPath = $this->upconfig[&#39;rootPath&#39;] . $this->upconfig[&#39;savePath&#39;];            if(!file_exists($fullPath)){                $ret = mkdir($fullPath, 0777, true);
            }            if(!$ret) {                // 上传错误提示错误信息
                $res[&#39;result&#39;] = 12;                $res[&#39;comment&#39;] = "创建保存图片的路径失败!";                return $res;                break;
            }            //开始上传
            if (file_put_contents($fullPath.$new_imgname, $string_image_content)){                // 上传成功 获取上传文件信息
                $res[&#39;result&#39;] = 0;                $res[&#39;comment&#39;] = "上传成功!";                $res[&#39;imgname&#39;] = $new_imgname;
            }else {                // 上传错误提示错误信息
                $res[&#39;result&#39;] = 11;                $res[&#39;comment&#39;] = "上传失败!";
            }


        } while(0);        return $res;
    }
Copy after login

方式二: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, &#39;DEBUG&#39;);        $file_log = print_r($_FILES, true);        Log::record($file_log, &#39;DEBUG&#39;);        $token = $_POST[&#39;token&#39;];        $token_str          = jwt_decode($token);$user_type          = $token_str[&#39;user_type&#39;];

        // 设置附件上传子目录
        if($user_type == 1) {            $savePath = &#39;travel/group/&#39; . $user_companyid . &#39;/&#39;;
        }elseif ($user_type == 2) {            $savePath = &#39;bus/group/&#39; . $user_companyid . &#39;/&#39;;
        }elseif ($user_type == 3) {            $savePath = &#39;driver/group/&#39; . $user_companyid . &#39;/&#39;;
        }else {            $array[&#39;status&#39;] = 3;            $array[&#39;comment&#39;] = &#39;非法用户!&#39;;            return $array;
        }        $this->upconfig[&#39;savePath&#39;] = $savePath;        // 保存上传的文件(单张)
//        $res = $this->upload($_FILES[&#39;file&#39;]);

    
        // 保存上传的文件(多张) 移动端的表单name=“xxx[]”,支持多张图片
        $res = $this->upload();        $array[&#39;status&#39;] = $res[&#39;status&#39;];        $array[&#39;comment&#39;] = $res[&#39;comment&#39;];        $array[&#39;responseParameters&#39;][&#39;img_url&#39;] = $res[&#39;img_url&#39;];        echo json_encode($array);
    }    protected function upload() {        $res[&#39;status&#39;] = 1;        $res[&#39;imgurl&#39;] = &#39;&#39;;        $res[&#39;comment&#39;] = &#39;&#39;;        do {            $ret = true;            $fullPath = $this->upconfig[&#39;rootPath&#39;] . $this->upconfig[&#39;savePath&#39;];            if(!file_exists($fullPath)){                $ret = mkdir($fullPath, 0777, true);
            }            if(!$ret) {                // 上传错误提示错误信息
                $res[&#39;status&#39;] = 1;                $res[&#39;comment&#39;] = "创建保存图片的路径失败!";                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", &#39;DEBUG&#39;);            $info_log = print_r($infos,true);            Log::record($info_log, &#39;DEBUG&#39;);            if(!$infos) {                // 上传错误提示错误信息
                $res[&#39;status&#39;] = 2;                $res[&#39;comment&#39;] = $upload->getError();
            } else {                // 获取的上传成功的图片数量
                $info_count = 0;                // 上传成功 获取上传文件信息
                foreach($infos as $k => $v) {                    $imgurl[$v[&#39;key&#39;]][] =  str_replace(&#39;./&#39;, &#39;/&#39;, $this->upconfig[&#39;rootPath&#39;] . $v[&#39;savepath&#39;].$v[&#39;savename&#39;]);                    $info_count += 1;
                }                if($file_count != $info_count) {                    $res[&#39;status&#39;] = 1;                    $res[&#39;comment&#39;] = "上传失败!上传的多张图片,没有全部上传成功";
                }else {                    $res[&#39;status&#39;] = 0;                    $res[&#39;comment&#39;] = "上传成功!";                    $res[&#39;img_url&#39;] = $imgurl;
                }
            }

        } while(0);        return $res;
    }
Copy after login

相关推荐:

相关推荐:

php 图片上传

图片和传真查看器 PHP 图片上传代码

PHP 图片上传代码_PHP教程

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles