PHP about AIP Image upload interface

Source: Internet
Author: User
Tags http post
simple examples of PHP uploads:

HTML file:



Style Related:

On the mobile side, click the Upload button to eject the camera:

    

<input type= "File" accept= "Image/*;capture=camera" > Direct call camera <input type= "file" accept= "image/*"/> Call phase Machine pictures or albums

PHP Files:

<?php$file = $_files[' file '];//gets the transmitted data//Gets the file name $name = $file [' name ']; $type = Strtolower (substr ($name, Strrpos ($name ,'.') +1)); Get the file type and convert it to lowercase $allow_type = array (' jpg ', ' jpeg ', ' gif ', ' PNG '); Defines the type of upload allowed//Determines whether the file type is allowed to upload if (!in_array ($type, $allow _type)) {    //If not allowed, then directly stop the program to run    return;} Determine if the IF (!is_uploaded_file ($file [' tmp_name ']) upload is uploaded via http POST {    //If the return is not uploaded via HTTP post    ;} $upload _path = "./img/"; Upload file path//Start move file to the appropriate folder if (Move_uploaded_file ($file [' Tmp_name '], $upload _path. $file [' name ']) {    echo ") Successfully! ";} else{    echo "failed!";}? >

Simple case of uploading with thinkphp upload class:

          = ' maxSize '    +    3145728,                 ' exts ' = ' + '    (' jpg ', ' gif ', ' PNG ', ' jpeg '),        ' rootpath '   = > '    ./public/uploads/info/',        ' savepath '   = '    , ' savename ' and '   =    ' Uniqid ', '),        ' autosub '    =    ,                               ' subname ' = '    (' Date ', ' YMD '),  upload ([' Result '] = 1[' imgurl '] = ' [' msg '] = ' = ' =  ->upconfig[' RootPath '].->upconfig[' Savepath ' (! (= (, 0777, (!
  [' result ' = 0[' msg '] = "failed to create path to save picture!" "             =  \think\upload (
(!                [' result '] = 0[' msg '] =                 -=  ->upconfig[' RootPath '). [' Savepath ']. [' Savename ' = ('./', '/', [' result '] = 1[' imgurl ') = (0          =->upload ([' attorney ']);

Mobile app upload Image instance: API interface:

Questions: App upload Avatar, PHP as the API side should be how to receive image information?

Uploading part of the code is not a problem, mainly the server side how to receive the app-side picture information. In the B/s architecture, you can set the Enctype= "Multipart/form-data" directly through the form form, and the image information is in the $_files array. So is it true in the C/s mode?

answer 1 (see mode one): generally using binary stream transmission, the client is binary, the server receives, and then file_put_contents write to the file. File name format, where files are placed, these own definitions.

Answer 2 (see mode II): The Android or iOS client simulates an HTTP POST request to the server side, after the server receives the corresponding POST request (obtains the picture resource through $_files), returns the response information to the client. (This is the same way you get HTML-submitted methods)

mode one: the picture is Base64 encrypted into a string, transmitted

Description: iOS or Android: by base64 the image to get the string, passed to the interface

interface: Base64 decode the received string and upload it to the specified location via the File_put_contents function

    /** * Image upload * @param $imginfo-image of the resource, array type. [' Picture type ', ' picture size ', ' Picture for Base64 encrypted string '] * @param $companyid-Company ID * @return Mixed */Public function Uploadima  GE ($imginfo, $companyid) {$image _type = strip_tags ($imginfo [0]);  Picture type $image _size = Intval ($imginfo [1]); Picture size $image _base64_content = Strip_tags ($imginfo [2]);        The picture is base64 encoded string $upload = new Uploaderservice ();        $upconfig = $upload->upconfig; if ($image _size > $upconfig [' maxSize ']) | | ($image _size = = 0))            {$array [' status '] = 13; $array [' comment '] = "picture size does not meet the requirements!"            ";        return $array;            } if (!in_array ($image _type, $upconfig [' exts '])) {$array [' status '] = 14; $array [' comment '] = "The picture format does not meet the requirements!"            ";        return $array; }//Set attachment upload subdirectory $savePath = ' bus/group/'. $companyid.        '/';        $upload->upconfig[' savepath ') = $savePath; The name of the picture saved $new _imgname = Uniqid (). Mt_Rand (100,999). '. '.        $image _type;        Base64 decoded picture string $string _image_content = Base64_decode ($image _base64_content);        Save uploaded file $array = $upload->upload ($string _image_content, $new _imgname);    return $array; }
    Upload configuration information Public $upconfig = Array (' maxSize ' = 3145728,//3145728b (bytes) = 3M ' exts ' = = Array (' jpg ', ' gif ', ' PNG ', ' jpeg '),//' rootpath ' = './public/uploads/info/', ' ROOTP    Ath ' = ' https://www.eyuebus.com/Public/Uploads/info/',); /** * @param $string _image_content-The string resource of the picture you want to upload * @param $new _imgname-the name of the picture, such as: 57c14e197e2d1744.jpg * @retu        RN 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) {//Upload error message error messages $res [' result '] = 12; $res [' comment '] = "failed to create the path to save the picture!"                ";    return $res;            Break }//Start uploading if (File_put_contents ($fullPath. $new _imgname, $string _image_content)) {//upload                Successful acquisition of uploaded file information $res [' result '] = 0; $res [' comment '] = "Upload succeeded!                ";            $res [' imgname '] = $new _imgname;                }else {//Upload error error message $res [' result '] = 11; $res [' comment '] = "Upload failed!            ";        }} while (0);    return $res; }

Mode two: Android or iOS client simulates an HTTP POST request to the server side, after the server receives the corresponding POST request (obtains the picture resource through $_files), returns the response information to the client. (This is the same way you get HTML-submitted methods)

The mobile need to request a URL, this URL to receive post past data, such as: 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 ']; Set the attachment Upload subdirectory 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 '] = ' illegal user!            ';        return $array;        } $this->upconfig[' savepath ' = $savePath;            Save uploaded file (leaflet)//$res = $this->upload ($_files[' file ');    Save uploaded file (multiple) mobile form name= "xxx[", support multiple pictures $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) {//Upload error message error messages $res [' status '] = 1; $res [' comment '] = "failed to create the path to save the picture!"                ";            Break }//Instantiate the Upload class $upload = new \think\upload ($this->upconfig);////Upload Single file//$in            fo = $upload->uploadone ($file);            Uploading multiple files $infos = $upload->upload ();            Number of images uploaded $file _count = 0; foreach ($_filesAs $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) {//Upload error error message $res [' status '] = 2;            $res [' comment '] = $upload->geterror ();                } else {//Gets the number of successful uploads $info _count = 0; Upload successfully get upload file information 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 '] = "Upload failed! UploadMany pictures, not all uploaded successfully ";                    }else {$res [' status '] = 0; $res [' comment '] = "Upload succeeded!                    ";                $res [' img_url '] = $imgurl;        }}} while (0);    return $res; }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.