让SAE下的wordpress支持文件上传

非PHP程序员照着源码打的小布丁…

SAE是不允许本地磁盘读写的,所以使用wordpress撰写文章的时候, 上传控件默认是用不了的,
幸好SAE提供了storage服务来存储文件,那就可以修改wordpress上传文件的实现,把文件存储到sae storage就可以了。

首先需要在SAE中开启storage服务,并创建一个 domain ,命名随意(后面会用到), 可看做是一个命名空间,或者是根目录。

然后修改wordpress的源码文件: wp-admin/includes/file.php ,
找到 wp_handle_upload函数,将原本上传部分的代码注释掉, 并添加几行代码来将文件上传到SAE Storage:

 319     /* 注释部分开始
 320     // A writable uploads dir will pass this test. Again, there's no point overriding this one.
 321     if ( ! ( ( $uploads = wp_upload_dir($time) ) && false === $uploads['error'] ) )
 322         return call_user_func($upload_error_handler, $file, $uploads['error'] );
 323 
 324     $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
 325 
 326     // Move the file to the uploads dir
 327     $new_file = $uploads['path'] . "/$filename";
 328     if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) )
 329         return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
 330 
 331     // Set correct file permissions
 332     $stat = stat( dirname( $new_file ));
 333     $perms = $stat['mode'] & 0000666;
 334     @ chmod( $new_file, $perms );
 335 
 336     // Compute the URL
 337     $url = $uploads['url'] . "/$filename";
 338     注释部分结束*/
 339 
 340     //新增部分开始 upload file to SAE Storage
 341     $fname = wp_unique_filename('', $file['name'], $unique_filename_callback);                                                                        
 342     $fname = "wordpress/" . date('Ymd') . "/" . $fname;                                                                                                                         
 343     $stor = new SaeStorage();
 344     $storRet = $stor->upload('codegallery',$fname, $file['tmp_name']);
 345 
 346     if(!$storRet) {
 347         return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to SAE STORAGE.' ) ) );
 348     }
 349     $url = $storRet;
 350     $new_file = $url;
         //新增部分结束

注意其中

$storRet = $stor->upload('codegallery',$fname, $file['tmp_name']);

是调用SAE Storage的API,
‘codegallery’ 就是之前我们创建的storage domain的名字, 需要根据实际情况修改.
$fname 是写入storage的文件名, 可以根据你想要的规则来修改, 我这里在原来的基础上, 把文件放到了 “wordpress/年月日” 命名的文件夹下.

就这么多, 将file.php更新到SAE版本库就可以了 :)

看一下效果:

可以正常的上传了;不过遗憾的是,图片的缩略图按钮点了没反应,由于我PHP完全是个小白,就忍了吧……

.........................................................我将必须获得世俗的成功...............................................
原文地址:https://www.cnblogs.com/idmask/p/4707957.html