欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-30 20:43:28
废话少说,直接上代码:

废话少说,直接上代码:

<?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!');
}
<?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方式上传,地址为:
另一个是multipart/form-data方式上传,地址为:
表单名称为"upload_file"。