Say, one of my needs is a temporary feature.Due to the problem of work development, we have a project B. We need a function to add commodities, which involves adding commodity content, such as commodity name, commodity description, commodity inventory, commodity picture, etc.Background merchandise added interface has been written, but the problem is that there is no background page at present, that is, the product has not yet been out of the background details page.The front end is ready to go online.Background work hours are also required.So the current approach is to add a function to add goods to project B in the background of our existing project A.
1. Current Issues
1. In our existing A project, there is no problem to add a new function to add commodities. Because the database of project B is already connected in project A, there is no problem to add or modify commodity attributes.Mainly the upload of merchandise pictures here, there is a problem.Project B already provides an external interface for uploading pictures, but because I am really not very familiar with the front end.So when I call up the interface for uploading pictures from project B in JS in project A, I always prompt "CORS". There should be a cross-domain problem here. Although I have already processed the cross-domain (entry file) on the PHP interface side, it seems that the JS side also needs to be adjusted accordingly.
// [ Apply Entry File ] //Entry file index.php namespace think; // Load Base File require __DIR__ . '/thinkphp/base.php'; // Supports static method settings in advance Request Object and Config object header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE,authorization"); // Execute application and respond Container::get('app')->bind('api')->run()->send();
2. Helplessly, Xiaobai JS is not solid enough, so I am here to try to complete the function by calling back-end PHP interface in project A, then accepting web-side parameters in PHP code, and then forwarding, calling the interface of uploading pictures in project B.The Postman interface tool is used to test whether the interface for uploading pictures from Project B is valid.As you can see in Figure 3, there is really nothing wrong and you are ready to do so.
3. But actually, when invoking, the commonly used upload parameters are GET or POST, but we know that file upload is accepted through $_FILES. Below is the controller code for project B's upload picture (using TP5.1) and the acceptance is through the built-in file method.
/**Upload pictures * @param Request $request */ public function uploadImg(Request $request){ $file = $request->file('image'); $type = $request->post('type', 0); // Move to Framework Application Root Directory/uploads/ Catalog $upload_path = config('common.upload_path'); switch ($type) { case 1://store $path = $upload_path['shop_img']; break; case 2://Voting Activities $path = $upload_path['vote_img']; break; case 3://Pictures of voting events $path = $upload_path['vote_contestant_img']; break; case 4://Member Store logo picture $path = $upload_path['member_shop']; break; case 5://Private Merchandise Picture $path = $upload_path['self_goods']; break; default: $path = $upload_path['common']; break; } $save_path = env('root_path').$path; $info = $file->validate(['ext'=>'jpg,jpeg,png,gif'])->move($save_path); if($info){ $return = [ 'extension' => $info->getExtension(), 'image_path' => $path.$info->getSaveName(), 'image_name' => $info->getFilename(), ]; $this->apiResult(CustomError::OPERATION_SUCCSESS, $return); }else{ $this->apiResult(CustomError::OPERATION_FAILED, [], $file->getError()); } }
4. So when I forward the content of the file from the web side of Project A, I am a little confused.Damn, Damn.
//File Upload Acceptance Parameters array(1) { ["file_upload"] => array(5) { ["name"] => string(8) "timg.jpg" ["type"] => string(10) "image/jpeg" ["tmp_name"] => string(22) "C:\Windows\php73CE.tmp" ["error"] => int(0) ["size"] => int(355565) } }
5. So as you have just imagined, it is not possible to simply forward. There should be another way of transferring these parameters, that is, the type of file.Given the success of uploading via Postman, this tool does recommend learning a lot. It not only verifies the availability of the interface as a third-party intermediate, but also provides us with various codes for the calling interface, Damo, where the Code identified in Figure 3 is the button to get Damo.We Click to see that Postman offers me three ways to invoke the interface.
<?php //1,HttpRequest Send out http request $request = new HttpRequest(); $request->setUrl('http://jszapi.dev.jingjinglego.com/index.php/index/uploadImg'); $request->setMethod(HTTP_METH_POST); $request->setHeaders(array( 'cache-control' => 'no-cache', 'Connection' => 'keep-alive', 'Content-Length' => '39091', 'Content-Type' => 'multipart/form-data; boundary=--------------------------296608706222243058746908', 'Accept-Encoding' => 'gzip, deflate', 'Host' => 'jszapi.dev.jingjinglego.com', 'Postman-Token' => 'dc010150-b166-4dec-a33f-959a65c91c71,be7315cb-ae21-404f-89fa-dddf5973eb3a', 'Cache-Control' => 'no-cache', 'Accept' => '*/*', 'User-Agent' => 'PostmanRuntime/7.15.2', 'content-type' => 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' )); $request->setBody('------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="image"; filename="785da43beca5a474.jpg" Content-Type: image/jpeg ------WebKitFormBoundary7MA4YWxkTrZu0gW--'); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }
<?php //2,pecl_http Need to be turned on PECL HTTP extend $client = new http\Client; $request = new http\Client\Request; $body = new http\Message\Body; $body->addForm(NULL, array( array( 'name' => 'image', 'type' => null, 'file' => '/E:/MyBooks/Site Icon/Site material/785da43beca5a474.jpg', 'data' => null ) )); $request->setRequestUrl('http://jszapi.dev.jingjinglego.com/index.php/index/uploadImg'); $request->setRequestMethod('POST'); $request->setBody($body); $request->setHeaders(array( 'cache-control' => 'no-cache', 'Connection' => 'keep-alive', 'Content-Length' => '39091', 'Content-Type' => 'multipart/form-data; boundary=--------------------------296608706222243058746908', 'Accept-Encoding' => 'gzip, deflate', 'Host' => 'jszapi.dev.jingjinglego.com', 'Postman-Token' => 'dc010150-b166-4dec-a33f-959a65c91c71,3216cc22-be61-4d4b-8d41-c5178848b54f', 'Cache-Control' => 'no-cache', 'Accept' => '*/*', 'User-Agent' => 'PostmanRuntime/7.15.2' )); $client->enqueue($request)->send(); $response = $client->getResponse(); echo $response->getBody();
<?php //3,cURL Is a very powerful open source library that supports many protocols, including HTTP,FTP,TELNET Wait, we use it to send HTTP Request.
//The advantage is that we can set different HTTP protocol parameters with flexible options and support HTTPS.CURL can automatically choose whether to encrypt the sent content based on whether the URL prefix is "HTTP" or "HTTPS". $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "http://jszapi.dev.jingjinglego.com/index.php/index/uploadImg", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"image\"; filename=\"785da43beca5a474.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", CURLOPT_HTTPHEADER => array( "Accept: */*", "Accept-Encoding: gzip, deflate", "Cache-Control: no-cache", "Connection: keep-alive", "Content-Length: 39091", "Content-Type: multipart/form-data; boundary=--------------------------296608706222243058746908", "Host: jszapi.dev.jingjinglego.com", "Postman-Token: dc010150-b166-4dec-a33f-959a65c91c71,982e059e-bd8b-4db9-83c4-3fd52c8ed82f", "User-Agent: PostmanRuntime/7.15.2", "cache-control: no-cache", "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; }
6. If the above three code snippets are used, but after verification, 1/3 of the parameters are found to be unknown how to transfer. The parameters of 2 are easy to understand, but the extension needs to be turned on. This is not appropriate at present, so.
2. Write in your heart
1. The uploaded question is really stuck and I feel a little sad.In fact, every time I encounter a difficulty of my own, I often encounter it. In the weekend afternoon, I open my computer at home, call remote, prepare to log on and drop down the FTP code, and find that I can't connect. I am upset.But the code was pulled down by the remote tool (Sunflower).I thought about how this picture was uploaded. I've seen it before, about uploading pictures by ftp, but later I saw an article that needs to be opened in php.ini, so I'll leave it as it is.
#open ftp Extended support extension=php_ftp.dll
2. I often encounter difficulties and often feel very LOW. However, I have been working for so long and found that in fact the problem was finally solved, but now I forget how to solve it, so I mainly want to write this blog.Until 4:00 p.m., the weather in Shenzhen is mostly muggy this year. I have taken an hour's lunch without my conscience at noon, so now I still feel a little guilty.
3. But there is still no solution. The headache is severe and the heat is good.What happened? I decided to rest on a chair, so I decided to lie down on the sofa and sleep.Just lying down, thinking about what to do.
----------------------------------------------------------------------------------------------------------------------------------------------------- gorgeous dividing line
I suddenly think of base64, a readable and easy-to-read function that converts pictures to base64 strings, passes them to project B by POST, decodes strings in project B, generates pictures, saves them to project B, and returns to the picture path. That's all.So I pushed it once and found no negligence.So I think it should be solved.
3. Solving the problem of uploading pictures
1. A accepts temporary pictures from the web,
#Upload Picture Beijing Finger 1:Keep pictures local public function uploadJszImg() {$path = config('business.jsz_file_tem'); $file = request()->file('file_upload'); $info = $file->validate(['ext'=>'jpg,jpeg,png,gif'])->move($path);//Save pictures locally $img_one = $path.$info->getSaveName();//Picture Path $img_base = imgToBase64($img_one);//Get Pictures base64 Encoding Format deleteFileWay($path);//Delete Temporary Files $url = config('business.jsz_api')['baseImg']; $data = [ 'base_string'=> $img_base, 'path' => 'upload/goods_img', ]; $res = http_api($url,$data,1); $res = json_decode($res,true); if($res['data']){ $return = ['code'=>1,'message'=>'Success','data'=>'jszapi.dev.jingjinglego.com'.$res['data']]; }else{ $return = ['code'=>0,'message'=>'fail']; } return $return; }
2. and convert to base64 string,
/** * Base64 encoding for getting pictures (url is not supported) * @param $img_file Incoming local picture address * @return string */ function imgToBase64($img_file) { $img_base64 = ''; if (file_exists($img_file)) { $app_img_file = $img_file; // Picture Path $img_info = getimagesize($app_img_file); // Get the size, type, etc. of the picture //echo '<pre>' . print_r($img_info, true) . '</pre><br>'; $fp = fopen($app_img_file, "r"); // Is the picture readable if ($fp) { $filesize = filesize($app_img_file); $content = fread($fp, $filesize); $file_content = chunk_split(base64_encode($content)); // base64 Code switch ($img_info[2]) { //Interpretation Picture Type case 1: $img_type = "gif"; break; case 2: $img_type = "jpg"; break; case 3: $img_type = "png"; break; } $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//Composite Picture base64 Code } fclose($fp); } return $img_base64; //Return pictures base64 }
3. B accepts parameters from item A
/** * Convert the base64 string to a picture and save it locally * @param Request $request * @return void */ public function baseImg(Request $request) { $base_string = $request->post('base_string', ''); if (!$base_string) { $this->apiResult(CustomError::MISSING_PARAMS); } $path = $request->post('path', ''); if (!$path) { $this->apiResult(CustomError::MISSING_PARAMS); } $request = base64_image_content($base_string, $path);//Decode if($request){ $this->apiResult(CustomError::OPERATION_SUCCSESS, $request); }else{ $this->apiResult(CustomError::OPERATION_FAILED); } }
4. Character parsing and decoding
/** * [Convert the Base64 picture to a local picture and save it] * @param [Base64] $base64_image_content [Base64 to save] * @param [Directory] $path [path to save] */ function base64_image_content($base64_image_content,$path){ //Match the format of the picture if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){ $type = $result[2]; $new_file = $path."/".date('Ymd',time())."/"; if(!file_exists($new_file)){ //Check to see if there is a folder, create it if not, and give it the highest permissions mkdir($new_file, 0700); } $new_file = $new_file.time().".{$type}"; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){ return '/'.$new_file; }else{ return false; } }else{ return false; } }
5. Return to the uploaded picture path at last
: End