服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - 美图秀秀web开放平台--PHP流式上传和表单上传示例分享

美图秀秀web开放平台--PHP流式上传和表单上传示例分享

2020-07-10 20:03PHP教程网 PHP教程

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

废话少说,直接上代码:

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

延伸 · 阅读

精彩推荐