PHP流式上传和表单上传(美图秀秀)

最近需要开发一个头像上传的功能,找了很多都需要授权的,后来找到了美图秀秀,功能非常好用。

01 <?php
02 /**
03  * Note:for octet-stream upload
04  * 这个是流式上传PHP文件
05  * Please be amended accordingly based on the actual situation
06  */
07 $post_input 'php://input';
08 $save_path = dirname(__FILE__);
09 $postdata file_get_contents($post_input);
10 if (isset($postdata) && strlen($postdata) > 0) {
11     $filename $save_path '/' . uniqid() . '.jpg';
12     $handle fopen($filename'w+');
13     fwrite($handle$postdata);
14     fclose($handle);
15     if (is_file($filename)) {
16         echo 'Image data save successed,file:' $filename;
17         exit ();
18     else {
19         die ('Image upload error!');
20     }
21 else {
22     die ('Image data not detected!');
23 }

 

01 <?php
02 /**
03  * Note:for multipart/form-data upload
04  * 这个是标准表单上传PHP文件
05  * Please be amended accordingly based on the actual situation
06  */
07 if (!$_FILES['Filedata']) {
08     die ('Image data not detected!');
09 }
10 if ($_FILES['Filedata']['error'] > 0) {
11     switch ($_FILES ['Filedata'] ['error']) {
12         case 1 :
13             $error_log 'The file is bigger than this PHP installation allows';
14             break;
15         case 2 :
16             $error_log 'The file is bigger than this form allows';
17             break;
18         case 3 :
19             $error_log 'Only part of the file was uploaded';
20             break;
21         case 4 :
22             $error_log 'No file was uploaded';
23             break;
24         default :
25             break;
26     }
27     die ('upload error:' $error_log);
28 else {
29     $img_data $_FILES['Filedata']['tmp_name'];
30     $size getimagesize($img_data);
31     $file_type $size['mime'];
32     if (!in_array($file_typearray('image/jpg''image/jpeg''image/pjpeg''image/png''image/gif'))) {
33         $error_log 'only allow jpg,png,gif';
34         die ('upload error:' $error_log);
35     }
36     switch ($file_type) {
37         case 'image/jpg' :
38         case 'image/jpeg' :
39         case 'image/pjpeg' :
40             $extension 'jpg';
41             break;
42         case 'image/png' :
43             $extension 'png';
44             break;
45         case 'image/gif' :
46             $extension 'gif';
47             break;
48     }
49 }
50  
51 if (!is_file($img_data)) {
52     die ('Image upload error!');
53 }
54  
55 // 图片保存路径,默认保存在该代码所在目录(可根据实际需求修改保存路径)
56 $save_path = dirname(__FILE__);
57 $uinqid = uniqid();
58 $filename $save_path '/' $uinqid '.' $extension;
59 $result = move_uploaded_file($img_data$filename);
60 if (!$result || !is_file($filename)) {
61     die ('Image upload error!');
62 }
63 echo 'Image data save successed,file:' $filename;
64 exit ();

 

备注:美图秀秀提供两个上传接口供测试

一个是octet-stream方式上传,地址为:http://imgkaka.meitu.com/xiuxiu_web_pic_save.php

另一个是multipart/form-data方式上传,地址为:http://web.upload.meitu.com/image_upload.php

表单名称为"upload_file" 。

你可能感兴趣的:(PHP流式上传和表单上传(美图秀秀))